以下不是完全相同的表,但我只是模拟表结构。
Table - Columns
Company - comp_id (primary), parent_id;
Department - comp_id, emp_id, dept_id(primary);
parent_id- one to many - comp_id;
comp_id - one to many - dept_id;
dept_id - one to many - emp_id;
requirement is to retrieve parent_id, count(dept_id), count(emp_id) group by parent_id
我尝试使用以下查询,但它要求使用可能妨碍性能的DISTINCT。
SELECT c.parent_id,
COUNT(DISTINCT c.comp_id),
COUNT(d.emp_id)
FROM company c
LEFT JOIN department d ON c.comp_id = d.comp_id
WHERE c.parent_id = ?
GROUP BY c.parent_id;
有人可以指定更好的方法吗?
答案 0 :(得分:0)
SELECT c.parent_id,COUNT(d.dept_id),COUNT(DISTINCT(d.emp_id))
FROM company c LEFT JOIN department d ON c.comp_id = d.comp_id
GROUP BY c.parent_id