php - 与 mysql 的左连接问题

标签 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   

最佳答案

我认为您需要切换连接的顺序,因此您将所有内容都保留在 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/

相关文章:

mysql - 如何用另一个值替换MySQL表中的列值

php - Codeigniter 2.1,MySQL - 将图像源插入数据库

mysql-proxy 0.8.3 负载均衡无法工作

sql - 多列索引效率

mysql - 计算一对多关系中存在多少

android sqlite 在 2 个不同的列中插入 2 个值

php - 如何将 JSON 对象发送到远程服务器并将该数据插入 MySQL 数据库

php - 节点中内容的 XPath 表达式,直到遇到带有字符串的节点

php - filemtime 找不到文件

php - Azure Key Vault 和托管身份 - 使用 REST 进行本地开发