我有三个表:
articles(id,title,message)
comments(id,article_id,commentedUser_id,comment)
comment_likes(id, likedUser_id, comment_id, action_like, action_dislike)
我想显示comments.id, comments.commentedUser_id, comments.comment, ( Select count(action_like) where action_like="like") as likes and comment_id=comments.id where comments.article_id=article.id
实际上,我想计算与任何评论相关的所有action_like。并显示所有文章评论。 action_likes只有两个值为null或like
SELECT c.id , c.CommentedUser_id , c.comment , (cl.COUNT(action_like) WHERE action_like='like' AND comment_id='c.id') as likes
FROM comment_likes as cl
LEFT JOIN comments as c ON c.id=cl.comment_id
WHERE c.article_id=article.id
它什么也没显示,我知道我做错了,那只是我想说的
答案 0 :(得分:2)
我想您正在寻找以下类似内容。这将返回“文章/评论”类别的“喜欢”计数。
SELECT
a.id article_id,
c.id comment_id,
c.CommentedUser_id ,
c.comment ,
COUNT (CASE WHEN action_like='like' THEN 1 ELSE NULL END) as likes
FROM article a
INNER JOIN comments C ON a.id = c.article_id
LEFT JOIN comment_likes as cl ON c.id=cl.comment_id
GROUP BY a.id,c.id , c.CommentedUser_id , c.comment
如果您需要特定文章的结果,则可以在GROUP BY部分之前添加WHERE子句,例如-WHERE a.id = N
答案 1 :(得分:-1)
我为此建议一个相关的子查询:
SELECT a.id as article_id, c.id as comment_id,
c.CommentedUser_id, c.comment,
(SELECT COUNT(*)
FROM comment_likes cl
WHERE cl.comment_id = c.id AND
cl.action_like = 'like'
) as num_likes
FROM article a INNER JOIN
comments c
ON a.id = c.article_id;
在这种情况下,相关子查询的性能通常比外部聚合要好得多,尤其是在索引正确的情况下。您想要的索引位于comment_likes(comment_id, action_like)
上。
为什么性能更好?大多数数据库将通过对数据进行排序来实现group by
。排序是一项昂贵的操作,它以超线性方式增长-也就是说,两倍的数据需要两倍多的时间来进行排序。
相关子查询将问题分解为较小的部分。实际上,不需要排序-只需扫描索引并计算匹配的行即可。