4个表上的SQL连接未返回正确的计数

时间:2018-05-01 17:59:10

标签: sql mariadb mariasql

我有4张桌子。

序列

id -> primary key
name 
user_id -> foreign key   (users id)

人:

id-> primary key
name-> varchar
seq_id -> foreign key from sequences
user_id -> foreign key from users

links_clicked:

id-> primary key
src_id -> foreign key (sequences id)
views -> Boolean

people_sequence

sequence_id-> foreign key   (sequences id)
people_id ->  foreign key   (people id)

我需要获取序列详细信息,链接表中的链接点击次数,seq_id所在的人数以及来自people_sequence表的序列中的序列计数。 我想我需要使用左连接,我编写了如下查询:

SELECT  sequences.*
       ,sum(link_clicked.view) as click_rate 
       ,count(people.seq_id) as prospect 
       ,count(people_sequences.sequence_id) as seqret 
FROM sequences 
LEFT JOIN link_clicked ON sequences.id=link_clicked.src_id 
LEFT JOIN people ON sequences.id=people.seq_id
LEFT JOIN people_sequences ON sequences.id=people_sequences.sequence_id
where sequences.user_id = 1
group by sequences.id

但这会将每个count列的计数返回为相同的

无法弄清楚SQL

的错误
id            | name |  user_id |click_rate |   prospect|seqret
5ac77be52d06e | seq1 |1         | 414       |    1890   | 1890
5ae790b48fea9 | seq2 |1         | 8         |    43     | 0
5ae790b6e0b12 | seq3 |1         | 2         |    0      | 0
5ae835c5153b5 | seq4 |1         | NULL      |    0      | 0

这是我得到的结果,但是如果我执行SQL,则视图的总和是不同的。并且计数也不同

SELECT `src_id` ,sum(`view`) FROM `link_clicked ` group by src_id

src_id         | sum(`view`)
5ac77be52d06e  | 23
5ae790b48fea9  | 8
5ae790b6e0b12  |2

1 个答案:

答案 0 :(得分:1)

我认为那些左连接会让你的结果变得疯狂...你会得到多个重复的条目,因为所有连接的排列都会产生结果导致无意义的总和/计数。要查看所有重复的结果,请删除聚合,您将获得一个极长的重复性和误导性列表。可以试试3个子查询吗?

SELECT S.*
       ,(SELECT COUNT(IIF([view], 1, 0)) FROM link_clicked WHERE src_id=S.id) click_rate
       ,(SELECT COUNT(*) FROM people WHERE seq_id=S.id) prospect
       ,(SELECT COUNT(*) FROM people_sequences WHERE sequence_id=S.id) seqret
FROM sequences S
WHERE S.user_id=1;