我有两个表并尝试根据主键和外键连接它们。但问题是在第二个表中外键有多个重复行。
结构:-
1 表 - 类别
catid catname
1 AAA
2 BBB
3 CCC
2 表 - 答案
ansid catid userid
1 1 9
2 1 9
3 2 9
4 2 6
结果应该是
userid catid catname present in answers table
null 1 AAA no
6 2 BBB yes
null 3 CCC no
我的查询是
SELECT a.userid, c.catid,c.catname,
case when sum(a.catid is not null) > 0
then 'yes' else 'no' end as present_in_answers_table
from answers a left join
category c on c.catid = a.catid
where (a.userid = 6) group by c.catid
但它没有返回我想要的结果。它只返回一行
userid catid catname present in answers table
6 2 BBB yes
最佳答案
我认为您需要切换连接的顺序,因此您将所有内容都保留在 category
表中,然后将 where
条件移动到 on
子句:
SELECT a.userid, c.catid, c.catname,
(case when count(a.catid) > 0 then 'yes' else 'no'
end) as present_in_answers_table
from category c left join
answers a
on c.catid = a.catid and
a.userid = 6
group by c.catid;
请注意,我还将 sum()
更改为 count()
-- count()
自动计算参数不是 NULL
。
关于php - 与 mysql 的左连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083293/