简体   繁体   English

mysql的左连接问题

[英]left join issue with mysql

I have two tables and trying to join both of them based on primary and foreign key.But the problem is that in second table the foreign key has multiple duplicate rows. 我有两个表并试图根据主键和外键将它们都连接起来,但是问题是在第二个表中外键有多个重复的行。

Structure :- 结构体 :-

1 Table - category 1张桌子-类别

catid   catname
1       AAA
2       BBB
3       CCC

2 Table - answers 2张桌子-答案

ansid    catid     userid
1        1         9
2        1         9
3        2         9
4        2         6

The result should be 结果应该是

userid    catid   catname   present in answers table
null       1         AAA       no
6          2         BBB       yes
null       3         CCC       no

My query is 我的查询是

    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

But it is not returning the results what I want.It returns only one row that is 但是它没有返回我想要的结果,它只返回一行

userid    catid   catname   present in answers table    
6          2         BBB       yes   

I think you need to switch the order of the joins, so you keep everything in the category table and then move the where condition to the on clause: 我认为您需要切换联接的顺序,因此您将所有内容保留在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;

Note that I also changed the sum() to a count() -- count() automatically counts the number of times the argument is not NULL . 请注意,我还将sum()更改为count()count()自动计算参数不为NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM