SQL连接3个表,同时从其中2个计数

时间:2018-03-20 22:07:39

标签: sql join

回到另一个关于联接的SQL问题。我有3张桌子:

user: id, username, name, city, state, private
rides: id, creator, title, datetime, city, state
posts: id, title, user, date, state, city

我需要从用户表中获取用户,并根据用户的ID获取每个人的帖子和游乐设施的数量。例如,id为25的用户有2个游乐设施和4个帖子,而id为27的用户有2个游乐设施和2个帖子。我遇到的问题是,两个用户都回来了4个帖子并且各自都有。

user.id = rides.creator = posts.user  //just so you know what fields equals the user id

这是我的代码:

select u.id, u.username, u.state, u.city, count(p.id) as TotalPosts, count(r.id) as TotalRides
from user u
left join posts p on p.user=u.id
left join rides r on r.creator=u.id
where private='public'
group by u.id
order by u.username, u.state asc;

如果我将它们分开,只是加入帖子或游乐设施,我会得到正确的总数。我尝试切换连接的顺序,但我得到了相同的结果。不知道发生了什么。

感谢任何想法或想法。

2 个答案:

答案 0 :(得分:1)

您的问题是两个不同维度的笛卡尔积。最好的解决方案是预先汇总数据:

select u.id, u.username, u.state, u.city, p.TotalPosts, r.TotalRides
from user u left join
     (select user, count(*) as totalposts
      from posts p
      group by user
     ) p
     on p.user = u.id left join
     (select creator, count(*) as totalrides
      from rides r
      group by creator
     ) r
     on r.creator = u.id
where u.private = 'public'
group by u.id
order by u.username, u.state asc;

答案 1 :(得分:0)

您可以随时使用子选择。

select u.*, (select count(*) from posts where user = u.id) as 'posts', (select count(*) from rides where creator = u.id) as 'rides' from users u where .....