简体   繁体   中英

How to sum the values of a column based on the result of another SELECT query?

I have the following tables: posts:

id   post
1   'p1'
2   'p2'
3   'p3'

comments:

id   comment post_id
1   'c1'     1
2   'c2'     1
3   'c3'     2

comments_likes:

id   comment_id   like
1    1            1
2    1            1
3    2           -1

I would like to run a query for a specific post (eg post_id = 1 and get the following:

comment_id   comment   likes   
1            'c1'       2
2            'c2'      -1
3            'c3'       0

I have tried a couple of queries with no luck: eg:

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;

or

SELECT c.*, cl.likes 
FROM comments c 
LEFT JOIN (
   SELECT comment_id, SUM(like) AS likes 
   FROM comments_likes
   ) cl ON cl.comment_id = c.id 
WHERE c.post_id = 1;

Does anyone have any idea how to do it in a single query?

you could try using a sum

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

or for all post

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 
ifnull(commnents_like,0)

IFNULL():如果表达式为NULL,则函数可返回一个替代值:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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