簡體   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