Php 获取所有评论,包括对帖子的投票
我在mysql中有以下三个表 posted| post|u content=>posts commentid| post | comment|u content=>comments commentvoteid | comment | voter=>评论投票 我想获取所有的Php 获取所有评论,包括对帖子的投票,php,mysql,sql,Php,Mysql,Sql,我在mysql中有以下三个表 posted| post|u content=>posts commentid| post | comment|u content=>comments commentvoteid | comment | voter=>评论投票 我想获取所有的评论,计票,用于帖子 commentid| comment|u内容| comment|u投票=>my|u结果 我尝试了以下查询,但没有得到所需的结果 SELECT commentid,comment_content,count_
评论
,计票
,用于帖子
commentid| comment|u内容| comment|u投票=>my|u结果
我尝试了以下查询,但没有得到所需的结果
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;
您可以使用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};
通常情况下,我更喜欢
分组方式
,但有时在MySQL中这会更快。您尝试的方法使用相关子查询。您可以这样做,但相关子查询需要进入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};
通常情况下,我更喜欢分组方式,但有时在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;
也许是这样:
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;
它起作用了,但我选择了@mesutozer的答案,正如你所说的
groupby
,非常感谢。它起作用了,但我选择了@mesutozer的答案,正如你所说的groupby
,非常感谢。它工作得很好,但我左加入
ed以获取评论投票
中尚不可用的评论。它工作得很好,但我左加入
ed以获取评论投票
中尚不可用的评论。