我有下表: 帖子:
const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3
评论:
id post
1 'p1'
2 'p2'
3 'p3'
comments_likes:
id comment post_id
1 'c1' 1
2 'c2' 1
3 'c3' 2
我想查询特定帖子(例如id comment_id like
1 1 1
2 1 1
3 2 -1
并获得以下信息:
post_id = 1
我尝试了几次运气不好的查询: 例如:
comment_id comment likes
1 'c1' 2
2 'c2' -1
3 'c3' 0
或
SELECT comment_id, SUM(like) AS likes
FROM comments_likes cl
RIGHT JOIN (
SELECT *
FROM comments
WHERE post_id=1
) c ON c.id = cl.comment_id;
有人知道如何在单个查询中做到这一点吗?
答案 0 :(得分:1)
您可以尝试使用总和
select id, comment, sum( ifnull(like,0) likes
from comments
left join comments_likes on a.id = comments_likes.comment_id
where post_id =1
group by id, comment
或针对所有帖子
select post.post, comments.id, comments.comment, sum( ifnull(commnents_like,0) likes
from post
inner join comments on post.id = comment.post_id
left join comments_likes on a.id = comments_likes.comment_id
group by post.post, comments.id, comments.comment
答案 1 :(得分:0)
ifnull(commnents_like,0)
IFNULL():如果表达式为NULL,则函数可返回一个替代值: