使用多个 table 联接获取 table 行计数
Get table row count using multiple table join
我有三个表 company_m
, client_m
, companyuser_m
company_m
CompanyID CompName
----------+-----------
7 Comp3
8 Comp2
9 Comp1
10 Company
11 Company4
client_m
clid AttachToCompanyID clname
-----+--------------------+------
1 7 client1
2 7 client2
6 8 client3
companyuser_m
uid CompanyID uname
---+---------+-------
1 7 user1
2 10 user2
我的目标
我需要获取对应公司的所有客户和用户的数量
预期输出
CompanyID CompName clientcount usercount
---------+-----------+--------------+--------
7 Comp3 2 1
8 Comp2 1 0
9 Comp1 0 0
10 Company 3 0 1
11 Company4 0 0
我的代码
select company_m.CompanyID,company_m.CompName,
count(client_m.AttachToCompanyID) as clientcount ,
count(companyuser_m.CompanyID) as usercount from company_m
left join client_m on client_m.AttachToCompanyID=company_m.CompanyID
left join companyuser_m on companyuser_m.CompanyID=company_m.CompanyID
group by company_m.CompanyID
但是上面的代码没有给出正确的输出。
查看我的fiddle
您应该加入单独的子查询,这些子查询在各自的 client_m
和 companyuser_m
表中查找计数:
SELECT
t1.CompanyID,
t1.CompName,
COALESCE(t2.cnt, 0) AS client_count,
COALESCE(t3.cnt, 0) AS user_count
FROM company_m t1
LEFT JOIN
(
SELECT AttachToCompanyID, COUNT(*) AS cnt
FROM client_m
GROUP BY AttachToCompanyID
) t2
ON t1.CompanyID = t2.AttachToCompanyID
LEFT JOIN
(
SELECT CompanyID, COUNT(*) AS cnt
FROM companyuser_m
GROUP BY CompanyID
) t3
ON t1.CompanyID = t3.CompanyID;
我有三个表 company_m
, client_m
, companyuser_m
company_m
CompanyID CompName
----------+-----------
7 Comp3
8 Comp2
9 Comp1
10 Company
11 Company4
client_m
clid AttachToCompanyID clname
-----+--------------------+------
1 7 client1
2 7 client2
6 8 client3
companyuser_m
uid CompanyID uname
---+---------+-------
1 7 user1
2 10 user2
我的目标
我需要获取对应公司的所有客户和用户的数量
预期输出
CompanyID CompName clientcount usercount
---------+-----------+--------------+--------
7 Comp3 2 1
8 Comp2 1 0
9 Comp1 0 0
10 Company 3 0 1
11 Company4 0 0
我的代码
select company_m.CompanyID,company_m.CompName,
count(client_m.AttachToCompanyID) as clientcount ,
count(companyuser_m.CompanyID) as usercount from company_m
left join client_m on client_m.AttachToCompanyID=company_m.CompanyID
left join companyuser_m on companyuser_m.CompanyID=company_m.CompanyID
group by company_m.CompanyID
但是上面的代码没有给出正确的输出。
查看我的fiddle
您应该加入单独的子查询,这些子查询在各自的 client_m
和 companyuser_m
表中查找计数:
SELECT
t1.CompanyID,
t1.CompName,
COALESCE(t2.cnt, 0) AS client_count,
COALESCE(t3.cnt, 0) AS user_count
FROM company_m t1
LEFT JOIN
(
SELECT AttachToCompanyID, COUNT(*) AS cnt
FROM client_m
GROUP BY AttachToCompanyID
) t2
ON t1.CompanyID = t2.AttachToCompanyID
LEFT JOIN
(
SELECT CompanyID, COUNT(*) AS cnt
FROM companyuser_m
GROUP BY CompanyID
) t3
ON t1.CompanyID = t3.CompanyID;