Tuesday 4 September 2018

mysql left join with count from the right table including zero

I have two tables as complaints and attachments

I want to list all complaints along with their attachment count (just counts). If no records found from right table (attachments) then 0 as attachment count.
I'm using this query,
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

But It just returns that rows which are present in right table (attachments table). I just want to list all rows from complaints table along with respective attachment count (If not count then 0).
Tables :
complaints
============
compl_id
cust_id
cust_msg
comp_date

attachments
============
pic_id
compl_id

EDIT:
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

I want to have results like this,
comp1   cust1   abcd    1/1/2015    0
comp2   cust5   hey     1/1/2015    2
comp3   cust60  hello   1/1/2015    0

But currently, I am getting result like this,
comp2   cust5   hey     1/1/2015    2


I think you just need a group by to get the desired results. MySQL extends aggregate functions to not require a group by. However, unless you know how to leverage this functionality, you'll likely get the wrong results most of the time. The only time to really use it is when all values in the column are the same; which I doubt is the case here.
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

0 comments:

Post a Comment