【发布时间】:2022-01-01 04:45:25
【问题描述】:
SELECT sg.date, sg.groupName, sg.highlights, user.display_name as displayName,
COUNT(*) as cmtcnt
FROM `saved_groups` as sg
LEFT JOIN `user` on user.email = sg.userName
LEFT JOIN `user_comments` as uc on sg.groupName = uc.groupName
GROUP BY sg.groupName
我有两个表,saved_groups 和 user_comments,查询的第二行应该(确实有效)返回一个额外的列,其中包含与每个组关联的 cmets 的数量。
但是,当一个组有 0 个与之关联的 cmets 时,计数应该返回 0 时返回 1。
如何解决这个问题?
我试过了:COUNT(*)-1 as cmtcnt——对于没有 cmets 的组返回零,但对于有关联 cmets 的组,它也返回一个不正确的数字 (-1)。
我也尝试过:NULL(Count(*), 0)——但 #1582 - Incorrect parameter count in the call to native function 'ISNULL' 出现错误
我也尝试过:COALESCE(COUNT(*), 0) as cmtcnt——这没有任何区别(所有组的 cmets 为零,返回 1,其他组返回正确的数字)
建议?
【问题讨论】:
-
一般情况下,最好把涉及的表的结构和一些示例数据贴出来。 dba.stackexchange.com 也是这类问题的好资源。