与mysql左连接问题

时间:2014-08-01 15:11:09

标签: php mysql sql

我有两个表,并尝试根据主键和外键加入它们。但问题是在第二个表中,外键有多个重复的行。

结构: -

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   

1 个答案:

答案 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的次数。