[英]mysql return count = 0 without joins using group by
我有一張桌子
Image
| ImageId | UserId | SourceId |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 1 |
| 6 | 3 | 1 |
| 7 | 3 | 1 |
| 8 | 3 | 1 |
| 9 | 3 | 1 |
然后我有一個查詢:
SELECT UserId, IFNULL( COUNT( ImageId ) , 0 ) AS ImageCount, SourceId
FROM Image
GROUP BY UserId, SourceId
當我進行查詢時,我得到了
| UserId | SourceId | ImageCount
| 1 | 1 | 1
| 1 | 2 | 1
| 2 | 1 | 1
| 1 | 2 | 1
| 3 | 1 | 5
但是,我不回來的那一行(我想要的)是:
| 3 | 1 | 0
即使計數為0,我該如何獲取行?
我看到的所有問題都必須處理連接(通常是左連接),但由於這不需要連接,所以我對如何解決這個問題感到困惑。
這確實需要left join
和更多。 您需要從所有可能的組合開始,然后使用left join
來引入現有值:
SELECT u.UserId, COUNT(i.ImageId ) AS ImageCount, s.SourceId
FROM (select distinct UserId from Image) u cross join
(select distinct SourceId from Image) s left join
Image i
on i.UserId = u.UserId and i.SourceId = s.SourceId
GROUP BY u.UserId, s.SourceId;
如果沒有匹配, count()
將返回0
。 不需要if
, coalesce
或case
語句。
這樣做是為了創建UserId
和SourceId
每種可能組合(基於Image
表中的值)。 然后使用left outer join
連接回圖像。 這是做什么的? 那么,對於現有記錄,它實際上什么都不做。 但對於未出現在表中的組合,它將在其他字段中添加帶有u.UserId
, s.SourceId
和NULL
的新行。 這是最終聚合的基礎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.