左连接的Mysql查询问题

时间:2014-07-24 22:34:21

标签: mysql sql

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

1表 - 类别

catid   catname
1       AAA
2       BBB
3       CCC

2表 - 答案

ansid    catid
1        1
2        1
3        2
4        2

结果应为

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

我的查询是

select * from category 
left join answers on category.catid=answers.catid
group by answers.catid

但它没有按照我想要的结果返回结果。

2 个答案:

答案 0 :(得分:1)

select c.catid, 
       c.catname, 
       case when sum(a.catid is not null) > 0
            then 'no' 
            else 'yes' 
       end as present_in_answers_table
from category c
left join answers a on c.catid = a.catid
group by c.catid, c.catname

答案 1 :(得分:1)

您可以尝试以下

select c.*,
case when a.ansid is null then 'no' else 'yes' end as `present in answers table`
from category c
left join answers a on c.catid = a.catid