Postgresql多表计数:喜欢,不喜欢,评论社交媒体风格的应用程序

时间:2017-11-12 17:48:37

标签: postgresql

尝试在postgresql中构建一个查询,以便为“帖子”提取评论,喜欢和不喜欢。目前,查询是错误计数的,并且当同一帖子发生两个评论/喜欢时,似乎会给出额外的值。

SQLFiddle可在此处获取:http://sqlfiddle.com/#!17/e0f51/1

目前,结果如下:

postid  postbody      comment_count dislikes    likes
1       Test Post A   1             0           0 
2       Test Post B   2             2           4
3       Test Post C   0             0           0
4       Test Post D   2             4           2
5       Test Post E   0             1           3

但理想情况下应该是这样的:

postid  postbody      comment_count dislikes    likes
1       Test Post A   1             0           0 
2       Test Post B   2             1           2
3       Test Post C   0             0           0
4       Test Post D   2             2           1
5       Test Post E   0             1           3

1 个答案:

答案 0 :(得分:1)

当有超过1条评论时,会出现问题,喜欢/不喜欢会乘以收到的评论数量。

最好的方法是将喜欢/不喜欢嵌入子查询而不是连接......

SELECT posts.postid, posts.postbody,
  COUNT(DISTINCT comments.commentid) AS comment_count, 
  (SELECT COUNT(nullif(postlikes.vote,true)) FROM postlikes WHERE postlikes.postid=posts.postid)  AS dislikes, 
  (SELECT COUNT(nullif(postlikes.vote,false))FROM postlikes WHERE postlikes.postid=posts.postid)  AS likes 
  FROM posts 
  LEFT JOIN comments ON comments.postid=posts.postid 
  GROUP BY posts.postid;