使用多个表联接获取表行数

时间:2019-06-28 05:28:31

标签: mysql join rowcount

我有三个表company_mclient_mcompanyuser_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

1 个答案:

答案 0 :(得分:2)

您应该连接到单独的子查询,这些子查询分别在client_mcompanyuser_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;