我有两个表格,分别是投诉
和附件
我想列出所有投诉及其附件数量(仅计数)。如果从右表(附件
)中找不到记录,则附件计数为 0。
我正在使用此查询,
SELECT c.*, IFNULL(COUNT(p.pic_id), 0) FROM complaints c
LEFT JOIN attachments p
ON c.compl_id = p.compl_id
ORDER BY comp_date DESC
但它只返回右表(附件
表)中存在的行。我只想列出 complaints
表中的所有行以及相应的附件计数(如果没有计数则为 0)。
表格:
complaints
============
compl_id
cust_id
cust_msg
comp_date
attachments
============
pic_id
compl_id
编辑:
complaints
===============
comp1 cust1 abcd 1/1/2015
comp2 cust5 hey 1/1/2015
comp3 cust60 hello 1/1/2015
attachments
===============
a_34554sdfs comp2
1_idgfdfg34 comp2
我想要这样的结果,
comp1 cust1 abcd 1/1/2015 0
comp2 cust5 hey 1/1/2015 2
comp3 cust60 hello 1/1/2015 0
但目前,我得到的结果是这样的,
comp2 cust5 hey 1/1/2015 2
最佳答案
我认为你只需要一个分组即可获得所需的结果。 MySQL 将聚合函数扩展为不需要分组依据。但是,除非您知道如何利用此功能,否则大多数时候您可能会得到错误的结果。真正使用它的唯一时间是当列中的所有值都相同时;我怀疑这里的情况就是这样。
SELECT compl_ID, cust_ID, cust_msg, comp_date, coalesce(count(Pic_ID),0) as Attach_Count
FROM complaints C
LEFT JOIN attachments A
on C.compl_ID = A.Compl_ID
GROUP BY compl_ID, cust_ID, cust_msg, comp_date
关于php - mysql左连接,右表计数包括零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31116251/