gpt4 book ai didi

sql - 来自多个表的sql count()

转载 作者:行者123 更新时间:2023-12-03 17:58:10 25 4
gpt4 key购买 nike

有这样的表:


图片:

wall_id|picture_id|user_id|likes
1| 1| 1| 2
1| 2| 1| 0
2| 1| 1| 1
2| 2| 2| 2



对(wall_id,picture_id)是唯一的


喜欢者:

wall_id|picture_id|user_id
1| 1| 3
1| 1| 2
2| 1| 2
2| 2| 4
2| 2| 3



我想要得到这样的东西:

    user_id|pictures_count|likes_count|likers_count
1| 3| 3| 2
2| 1| 2| 2


我尝试了这个:

select p.user_id as user_id, 
count(p.user_id) as pictures_count,
sum(p.likes) as likes_count,
count(distinct l.user_id) as likers_count
from pictures p
left join likers l on p.wall_id = l.wall_id
and p.picture_id = l.picture_id
group by p.user_id




select pictures.user_id, count(pictures.user_id) as pictures_count,
sum(pictures.likes) as likes_count,
count(distinct likers.user_id) as likers_count
from pictures, likers
where pictures.picture_id = likers.picture_id
and pictures.user_id = likers.user_id
group by pictures.user_id


但是我得到这样的结果:

    user_id|pictures_count|likes_count|likers_count
1| 4| 6| 2
2| 2| 4| 2


我应该怎么做才能得到正确的结果?

最佳答案

Join是件奇怪的事情。当您有一个键并且两边都匹配多行时,您会得到更多的期望行。解决方案是预聚集每一侧的行。

数据模型有点复杂,因为您需要join来查找likes表的用户ID。

 select p.user_id as user_id, p.pictures_count, p.likes_count, l.likers_count
from (select p.user_id, count(*) as pictures_count, sum(likes) as likes_count
from pictures p
group by p.user_id
) p left join
(select p.user_id, count(distinct l.user_id) as likers_count
from pictures p left join
likers l
on p.wall_id = l.wall_id and p.picture_id = l.picture_id
group by p.user_id
) l
on p.user_id = l.user_id;


注意,由于聚合是在子查询中完成的,因此外部查询中不再需要它。

关于sql - 来自多个表的sql count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28740703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com