使用外键计算行数

时间:2015-07-07 16:33:08

标签: sql sqlite android-sqlite

我在Android上使用sqlite3。我试图找到与结果中每行相关的行数。以下内容反映了表格的一般组织,但细节更为复杂:

部门:

+----+-----------------+
| id | name            | 
+----+-----------------+

雇员:

+----+-----------------+-----------------+
| id | dept_id         | name            |
+----+-----------------+-----------------+

管理器:

+----+-----------------+-----------------+
| id | dept_id         | name            |
+----+-----------------+-----------------+

我正在尝试查询所有部门,并且每个部门都显示1)员工和2)经理的计数。因此结果可能类似于:

id | name | num_employees | num_managers
1  | IBM  | 10000         | 800
2  | FB   | 8000          | 20

我想在一个查询中执行此操作,以便我可以使用单个CursorLoader。我试过这个,但它不对:

SELECT d.id, d.name, COUNT(e.id), COUNT(m.id)
FROM dept d 
INNER JOIN employee e ON d.id = e.dept_id 
INNER JOIN manager m ON d.id = m.dept_id 
GROUP BY d.id;

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

加入employeemanager会产生员工和经理的所有可能组合。 您可以使用COUNT(DISTINCT)仅计算这些的唯一出现次数:

SELECT d.id,
       d.name,
       COUNT(DISTINCT e.id) AS num_employees,
       COUNT(DISTINCT m.id) AS num_managers
FROM dept AS d
JOIN employee AS e ON d.id = e.dept_id
JOIN manager  AS m ON d.id = m.dept_id
GROUP BY dept.id

然而,生成所有这些组合,只是为了以后过滤它们是低效的。

您可以使用correlated subqueries

分别计算点数
SELECT id,
       name,
       (SELECT COUNT(*)
        FROM employee
        WHERE dept_id = dept.id
       ) AS num_employees,
       (SELECT COUNT(*)
        FROM manager
        WHERE dept_id = dept.id
       ) AS num_managers
FROM dept

答案 1 :(得分:0)

select dept.id, dept.name, e.num_employees , m.num_managers
from dept
left join (select count(*) as num_employees, dept_id from employee group by dept_id) e
on
dept.id = e.dept_id
left join (select count(*) as num_managers, dept_id from manager group by dept_id) m
on
dept.id = m.dept_id