我有两个表(post.id是主键,在like.post_id中成为次要键)
表格“发布”
id user_id image
1 10 abc.jpg
2 20 xyz.jpg
3 10 ajb.jpg
表“赞”
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
现在我希望每当我通过user_id时,我都希望获得具有喜欢的帖子数的所有用户帖子
我尝试了以下代码,但没有用,
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'
我该怎么做?我想要以下结果(如果我通过user_id = 10)
user_id post_id likes
10 1 3
10 3 1
答案 0 :(得分: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;
答案 1 :(得分:0)
您可以使用聚合:
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
即使这是一个si.*
查询,您也可以在select
中使用group by
,因为您正在按表中的主键/唯一ID进行汇总。
答案 2 :(得分:0)
表“ like”中有所有必要的数据 您可以从“喜欢”表中选择一个。
select user_id, post_id, sum(likes) as likes from like where user_id = 10;
您需要计数或加总? 取决于您的需求您可以求和(点赞)或计数(*)点赞