JOINS 和 Distinct 查询

发布于 2024-11-05 18:35:08 字数 617 浏览 1 评论 0原文

以下不是完全相同的表,但我只是模拟表结构。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

︶ ̄淡然 2024-11-12 18:35:08
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文