0

我有 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

链接点击:

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

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

无法弄清楚 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
4

1 回答 1

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;
于 2018-05-05T13:47:44.623 回答