1

我有四个包含一些字段的表

1. user(id, name, email, password, .....)
2. policy1(id, userid, ....)
3. policy2(id, userid, ....)
4. policy3(id, userid, ....)

现在很清楚,用户的主键 (id)是其他三个表中的外键

我想针对包含该表中的用户的每个用户获取表的总数id

例如:

user id 1 has entry in any two tables, 
user id 2 has entry in three tables, 
user id 3 has entry in any single table

结果应该像

id    total
1     2
2     3
3     1

我尝试使用Left Join,但我无法获得预期的结果。

4

1 回答 1

1

您可以使用子查询来获取每个用户的计数,然后将这些值相加以获得最终结果。即使其他表中没有匹配的值,我也使用 aLEFT JOIN返回所有行。user如果您只希望用户在其他表中具有值,那么您可以使用INNER JOIN

select u.id,
  Coalesce(CntP1, 0) + Coalesce(CntP2, 0) + Coalesce(CntP3, 0) TotalCount
from `user` u
left join
(
  select count(*) CntP1, userid
  from policy1
  group by userid
) p1
  on u.id = p1.userid
left join
(
  select count(*) CntP2, userid
  from policy2
  group by userid
) p2
  on u.id = p2.userid
left join
(
  select count(*) CntP3, userid
  from policy3
  group by userid
) p3
  on u.id = p3.userid
于 2013-01-18T11:03:47.623 回答