如何使用外键从不同的表中选择计数?

时间:2016-03-11 10:13:22

标签: mysql sql postgresql

city
----------------------
id    city_name
1     Pune
2     Mumbai
3     Banglore

Branches
----------------------
id    branch_name     city_id
1     Magarpatta      1
2     Wagholi         1
3     Kurla           2
4     CST             2
5     Thane           2
6     Anekal          3

Employees
----------------------
id    employee_name   city_id
1     Arun            1
2     Varun           1
3     Mahesh          2
4     Umesh           2
5     Prakash         1
6     Kedar           3

Expected result
-----------------------------
id(city) city_name  No_of_Branch  no_of_employee
1        Pune       2             3
2        Mumbai     3             2
3        Banglore   1             1

我可以在单个查询中获得以上结果吗? 我可以在这种情况下使用交叉表吗?怎么样?

2 个答案:

答案 0 :(得分:1)

<f:ajax listener="#{productBean.refresh}" render="products" onevent="GENERIC.productsLoaded"/>

或者

    SELECT c.*, count(DISTINCT b.id) AS No_of_Branch, count(DISTINCT e.id) AS no_of_employee
       FROM city c 
         LEFT JOIN branches  b ON (b.city_id=c.id)
         LEFT JOIN employees e ON (e.city_id=c.id)
    GROUP BY c.id

答案 1 :(得分:0)

试试这个:

 SELECT c.id, c.city_name,
        COUNT(b.id) AS No_of_Branch, 
        no_of_employee
 FROM city c 
 LEFT JOIN branches b ON b.city_id = c.id
 LEFT JOIN (
   SELECT city_id, COUNT(e.id) AS no_of_employee
   FROM employees AS e
   GROUP BY e.city_id
 ) AS e_grp  ON e_grp.city_id = c.id
 GROUP BY c.id, c.city_name

这里的技巧是使用包含每city_id个雇员数量的派生表。我只是将所有表格加在一起,最终会有重复的员工数量。

Demo here