在三个表中使用count和group by进行SQL查询

时间:2016-01-06 17:09:01

标签: php mysql sql

我正在进行sql查询,其中有三个表帖子,用户和评论。我想显示所有帖子及其用户和评论数量。我有以下查询,但它给了我错误的结果:

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

除了上述查询,我​​还需要来自users表的firstname和lastname。

2 个答案:

答案 0 :(得分:0)

尝试类似的方法

 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

答案 1 :(得分:-1)

尝试以下内容:

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。该小组所做的是,它将选择所有唯一的帖子,并且计数将返回该一个唯一帖子的用户数量