mysql左连接与右表的计数包括零

时间:2015-06-29 12:52:56

标签: php mysql sql database

我有两个表complaintsattachments

我想列出所有投诉及其附件计数(只是计数)。如果没有从右表(attachments)找到记录,则将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

但它只返回右表(attachments表)中存在的行。我只想列出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

3 个答案:

答案 0 :(得分:3)

我认为您只需要一个小组来获得所需的结果。 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

答案 1 :(得分:0)

你可以尝试这个,删除IFNULL:

SELECT c.*, COUNT(p.pic_id)
FROM complaints c
LEFT JOIN attachments p
ON c.compl_id = p.compl_id 
ORDER BY comp_date DESC

答案 2 :(得分:0)

你想要的是:

SELECT c.*, COUNT(c.compl_id) AS count
FROM complaints c
INNER JOIN attachments a USING(compl_id)
GROUP BY c.compl_id;
相关问题