MySQL:来自多个表的COUNT()

时间:2019-01-31 15:30:17

标签: mysql sql

我有3个表userpersoncompany
user_idforeign keyperson表中的company
我要做的是计算与每个用户相关的人数和公司,所以我做了以下查询:

select u.id , u.username, count(c.user_id) as count_company, count(p.user_id) as count_people
from user u left join company c on (u.id = c.user_id)
left join person p on (u.id = p.user_id)
group by u.id, u.username

但是我得到错误的结果!!
这是我得到的结果:
enter image description here

但是,当我尝试使用此查询仅计算与每个用户相关的公司时:

select u.id , u.username, count(c.staff_user_id) as count_company
from fos_user u left join company c on (u.id = c.staff_user_id)
group by u.id, u.username

我得到这个结果:
enter image description here
我在这里想念什么?

2 个答案:

答案 0 :(得分:3)

如果用户与多个公司和/或多个人相关,那么您始终要对他们的交叉联接进行计数-这就是公司数量乘以人数。

>

要解决该问题(针对您的情况),我将使用子查询:

select u.id, u.username, 
    (select count(*) from company c where u.id = c.user_id) as count_company,
    (select count(*) from person p  where u.id = p.user_id) as count_people
from user u

请注意,像查询中那样的双重联接从关系的角度来看(在大多数情况下)只是错误的。

答案 1 :(得分:0)

似乎您需要不同的计数

select u.id 
    , u.username
    , count(distinct c.user_id) as count_company
    , count(distinct p.user_id) as count_people
from user u 
left join company c on (u.id = c.user_id)
left join person p on (u.id = p.user_id)
group by u.id, u.username

count(col)计算col中非null的值... count(distinct col)计算col1的不同值