加入 3 个表的查询

join query with 3 tables

我在 mysql 中有 3 个表:

t_group:

id | groupid
--------------
1    group1      
2    group2

t_user:

id | userid | groupid
----------------------
1    user1    group1  
2    user2    group1
3    user3    group2
4    user4    group2
5    user5    group2

t_order:

id | orderid | userid
---------------------
1    order1    user1      
2    order2    user2
3    order3    user2
4    order4    user4

我喜欢按组获取用户数和订单数。 我的查询如下:

SELECT t_group.groupid, COUNT(t_user.id) as num_user, COUNT(t_order.userid) as num_order
FROM `t_group` 
left join t_user on t_group.groupid=t_user.groupid
left join t_order on t_order.userid=t_user.userid
GROUP by t_group.groupid

但我得到了奇怪的结果:

------------------------------
groupid | num_user | num_order
------------------------------
group1    3          3 
group2    3          1  

group1的实际用户数为2,但显示为3。 难道不能在单个连接查询中得到我想要的结果吗?

尝试使用内部联接:

SELECT t_group.groupid, COUNT(t_user.id) as num_user, COUNT(t_order.userid) as num_order FROM `t_group` 
INNER JOIN t_user ON t_group.groupid=t_user.groupid
INNER JOIN t_order ON t_order.userid=t_user.userid
GROUP by t_group.groupid

您可以尝试这种方法来达到预期的效果:

select temp1.groupid,temp1.count_user,temp2.count_order from 
  (select count(distinct (u.userid)) count_user, u.groupid
   from t_group g
   inner join t_user u on u.groupid= g.groupid
   group by u.groupid
  ) temp1
left join
  (select count(distinct (o.orderid))count_order, u.groupid
  from t_group g
  inner join t_user u on u.groupid= g.groupid
  inner join t_order o on u.userid = o.userid 
  group by u.groupid
  ) temp2
on temp1.groupid= temp2.groupid
order by temp1.groupid;

DB Fiddle