繁体   English   中英

获得所有评论,包括其对某票的投票

[英]get all comments including its votes for a post

我在mysql有以下三个表。

postid | post_content => 帖子

commentid | 发布| comment_content => 评论

评论| 评论| 选民=> comment_votes

我想获取所有的commentscounting its votespost

commentid | comment_content | comment_votes => my_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}

是否可以根据需要获取结果? 我怎样才能做到这一点?

您可以使用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;

您正在尝试的方法使用相关的子查询。 您可以执行此操作,但是相关的子查询需要进入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};

通常,我更喜欢采用group by方式,但有时在MySQL中这可以更快。

也许像这样:

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.

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