从另一个表计数的SQL

时间:2014-01-18 11:44:09

标签: mysql sql select count

我正在管理用户可以喜欢的社交网络数据库,评论并为帖子创建了一个表格,例如和评论。

like --- post_id
         user_id

comment --- post_id
            user_id

现在,当我运行select * from post时,我希望能够添加两列likescomments来计算每个post_id的喜欢和评论的数量。

我该怎么做?

4 个答案:

答案 0 :(得分:5)

您需要加入两个表格。

SELECT post.*, COUNT(likes.id) AS like_count, COUNT(comment.id) AS comment_count
FROM post
    LEFT JOIN likes ON post.id = likes.post_id
    LEFT JOIN comment ON post.id = comment.post_id
GROUP BY post.id

答案 1 :(得分:5)

像这样:

SELECT *
,    (SELECT COUNT(*) FROM likes WHERE post_id=p.id) as LIKE_COUNT
,    (SELECT COUNT(*) FROM comment WHERE post_id=p.id) as COMMENT_COUNT
FROM post p

Demo on sqlfiddle.

答案 2 :(得分:4)

SELECT post.id, COUNT(like.id) AS like_count, COUNT(comment.id) AS comment_count
FROM post p
    LEFT JOIN like ON post.id = like.post_id
    LEFT JOIN comment ON post.id = comment.post_id
GROUP BY post.id

它类似于@Richard的回答,但修改了select,因为group by中的列必须位于select子句中。

答案 3 :(得分:3)

SELECT
  post.*,
  IFNULL(COUNT(like.user_id),0) AS likecount,
  IFNULL(COUNT(comment.user_id),0) AS commentcount
FROM
  post
  LEFT JOIN like ON post.post_id=like.post_id
  LEFT JOIN comment ON post.post_id=comment.post_id
GROUP BY
  like.post_id