【发布时间】:2021-02-22 20:22:18
【问题描述】:
我有以下疑问:
SELECT dtr_user.username,
dtr_user.loggedin,
dtr_user.profilepicture,
dtr_siterank.siterankname,
dtr_user.joindate,
COUNT(forum_post.postid),
COUNT(dtr_entries.entreeid)
FROM dtr_user,
forum_post,
dtr_entries,
dtr_siterank
WHERE dtr_user.userid = ?
AND dtr_user.userid = dtr_entries.entreeauthor
AND dtr_user.userid = forum_post.userid
AND dtr_user.siterank = dtr_siterank.siterankid
所以我希望它返回海报的 postid.s 计数,与主菜 id 的计数相同
当我运行SELECT COUNT(forum_post.postid) FROM forum_post where forum_post.userid = 1 时,它返回正确的数字(17),与返回4 的SELECT COUNT(dtr_entries.entreeid) FROM dtr_entries where dtr_entries.entreeauthor = 1 相同
然而,在主查询中,这两个数字都出现了68。我是否对此应用左连接?查询真的不是我的弦乐。
【问题讨论】:
-
计数正在成倍增加,因为连接为每个帖子返回 4 行。
-
也许你的意思是
COUNT(DISTINCT ...)?没有 distinct 的 COUNT() 只计算参数不为空的次数,这就是你的两个 id 相等的原因。
标签: mysql sql count inner-join aggregate-functions