[英]get all comments including its votes for a post
I have following three tables in mysql
. 我在
mysql
有以下三个表。
postid |
postid | post_content => posts
post_content => 帖子
commentid |
commentid | post |
发布| comment_content => comments
comment_content => 评论
commentvoteid |
评论| comment |
评论| voter => comment_votes
选民=> comment_votes
I want to fetch all the comments
, counting its votes
for a post
. 我想获取所有的
comments
, counting its votes
的post
。
commentid |
commentid | comment_content |
comment_content | comment_votes => my_result
comment_votes => my_result
I have tried the following query but not getting the desired result. 我尝试了以下查询,但未获得所需的结果。
SELECT commentid,comment_content,count_comments.total AS comment_votes
FROM comments
INNER JOIN(SELECT COUNT(*) AS total FROM comment_votes WHERE comment=comments.commentid) AS count_comments
WHERE post={$postId}
Is it possible to fetch the result as I wanted? 是否可以根据需要获取结果? How can I do that?
我怎样才能做到这一点?
You can use GROUP BY to achieve what you want: 您可以使用GROUP BY实现所需的功能:
SELECT commentid,comment_content,COUNT(*) AS total
FROM comments
INNER JOIN comment_votes ON (comment_votes.comment=comments.commentid)
WHERE post={$postId}
GROUP BY commentid;
The method that you are trying uses a correlated subquery. 您正在尝试的方法使用相关的子查询。 You can do this, but the correlated subquery needs to go into the
select
clause: 您可以执行此操作,但是相关的子查询需要进入
select
子句:
SELECT c.commentid, c.comment_content,
(SELECT COUNT(*) FROM comment_votes cv WHERE cv.comment = c.commentid
) AS comment_votes
FROM comments c
WHERE post={$postId};
Normally, I much prefer the group by
approach but sometimes in MySQL this can be faster. 通常,我更喜欢采用
group by
方式,但有时在MySQL中这可以更快。
maybe like this: 也许像这样:
select a.commentid, a.comment_content, count(b.*) as total from (
select commentid, comment_content from comments where post={$postId}) a
join comment_votes b on b.comment = a.commentid
group by a.commentid, a.comment_content;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.