繁体   English   中英

在三个表中进行计数和分组的SQL查询

[英]SQL query with count and group by in three tables

我正在处理一个SQL查询,其中有三个表帖子,用户和注释。 我想显示所有帖子及其用户和对此的评论数量。 我有以下查询,但它给我错误的结果:

SELECT 
c.userid, count(c.userid), p.postid 
FROM comments c, posts p 
where c.userid = p.userid group by c.userid

除了上述查询外,我还需要用户表中的名字和姓氏。

试试这个

 SELECT 
    u.userid, u.firstname, u.lastname,p.post, p.postid, 
    count(c.userid) totalcoments  -- may be c.commentid
    FROM users u 
    JOIN posts p  ON p.userid=u.userid
    LEFT JOIN  comments c OM c.postid=p.postid
    GROUP BY u.userid, u.firstname, u.lastname,p.post, p.postid

尝试如下操作:

SELECT 
    postid
    , p.userid 
    , COALESCE((
        SELECT COUNT( * ) FROM comments WHERE postid = p.id 
    ), 0 ) AS cnt_postid
    , COALESCE( ( SELECT CONCAT( firstname, ' ', lastname ) FROM users WHERE userid = p.userid ), 'N/A' ) AS NAME
FROM posts p 
    LEFT JOIN comments c ON c.postid = p.id
GROUP BY postid 
ORDER BY postid

您可能会获得相同数量的计数,因为您没有使用分组依据。

使用聚合函数时,必须始终使用GROUP BY group by的作用是它将选择所有唯一帖子,并且计数将返回该唯一帖子的用户数量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM