Soh*_*tel 2 php mysql sql database
我有两个表作为complaints和attachments
我想列出所有投诉及其附件数量(仅计算)。如果从右表 ( 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
Run Code Online (Sandbox Code Playgroud)
attachments但它只是返回右表(表)中存在的行。我只想列出complaints表中的所有行以及相应的附件计数(如果不计数则为 0)。
表格:
complaints
============
compl_id
cust_id
cust_msg
comp_date
attachments
============
pic_id
compl_id
Run Code Online (Sandbox Code Playgroud)
编辑:
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
Run Code Online (Sandbox Code Playgroud)
我想要有这样的结果
comp1 cust1 abcd 1/1/2015 0
comp2 cust5 hey 1/1/2015 2
comp3 cust60 hello 1/1/2015 0
Run Code Online (Sandbox Code Playgroud)
但目前,我得到这样的结果,
comp2 cust5 hey 1/1/2015 2
Run Code Online (Sandbox Code Playgroud)
我认为你只需要一个分组即可获得所需的结果。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
Run Code Online (Sandbox Code Playgroud)