JOINS 和 Distinct 查询
以下不是完全相同的表,但我只是模拟表结构。
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;
有人可以指定更好的方法吗?
Following are not exactly the same tables, but I'm just simulating the table structure.
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
I tried with the following query, but it demands using DISTINCT which might hamper performance.
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;
Can someone please specify a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)