简体   繁体   中英

Count in Joins in SQL

i have two tables (post.id is primary key which become seconday key in like.post_id )

table "post"

id      user_id     image
1       10          abc.jpg
2       20          xyz.jpg
3       10          ajb.jpg

Table "Like"

id      user_id     post_id         likes
1       10          1               1
2       20          2               1
3       10          1               1
4       10          1               1
3       10          3               1

now i want whenever i pass user_id then i wan to get all post of users with number of likes of posts

i tried with following code but not worked,

SELECT selfie_info.id,selfie_info.user_id,selfie_info.image, (SELECT COUNT(m.likes)FROM post_likes m WHERE m.user_id='10') as total_likes FROM selfie_info where user_id='10'

how can i do this ? i want result like following (if i pass user_id=10 )

user_id     post_id     likes
10          1           3
10          3           1
SELECT p.user_id, p.id AS post_id, COUNT(l.id) AS total_likes
FROM post p
LEFT JOIN likes l ON l.post_id =p.id
WHERE p.user_id=10 GROUP BY p.id;

You can use aggregation:

select pl.post_id, count(*) as numlikes,
       si.*
from selfie_info si join
     post_likes pl
     on si.user_id = pl.user_id
where si.user_id = 10
group by si.user_id, si.post_id

You can use si.* in the select , even though this is a group by query because you are aggregating by the primary key/unique id in the table.

You have all necessary data in table "like" You can use one select from "like" table.

select user_id, post_id, sum(likes) as likes from like where user_id = 10;

You need to count or sum likes? Depends on you needs You can sum(likes) or count(*) likes

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