我有两个表,并尝试根据主键和外键加入它们。但问题是在第二个表中,外键有多个重复的行。
结构: -
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
答案 0 :(得分:3)
我认为您需要切换联接的顺序,因此您将所有内容保留在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
的次数。