[英]mysql left join with count from right table including zero
我有兩張桌子作為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
但它只返回右表( 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
我想你只需要一組來獲得理想的結果。 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
您可以嘗試這個,刪除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
你想要的是:
SELECT c.*, COUNT(c.compl_id) AS count
FROM complaints c
INNER JOIN attachments a USING(compl_id)
GROUP BY c.compl_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.