我有桌子
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
在其他领域。这是最终汇总的基础。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句