mysql - 将表连接到自身时避免重复
问题描述
我确定答案已经存在,但我正在努力将足够相似的帖子应用于我的具体问题。请多多包涵。
我有一个使用 id_parent_job 字段引用自身的作业表。童工有许多空缺。
id id_parent_job is_active num_openings
1 1 y NULL
2 1 n 15
3 1 y 10
4 4 y NULL
5 4 n 13
6 6 y NULL
7 6 y 15
8 6 n 15
9 6 y 15
给定父职位 ID,我想找到 2 个数字:职位空缺总和和有效职位空缺总和。这是期望的结果。我需要查询方面的帮助。
job 1: 25 openings, 10 active openings
job 4: 13 openings, 0 active openings
job 6: 45 openings, 30 active openings
下面是我正在使用的查询,但它会导致重复。这是(也许?)对问题的一个很好的解释。
SELECT jobs.id, SUM(childjobs.num_openings), SUM(activechildjobs.num_openings) FROM jobs
LEFT JOIN jobs AS childjobs
ON childjobs.id_parent_job = jobs.id
AND childjobs.id != jobs.id
LEFT JOIN jobs AS activechildjobs
ON activechildjobs.id_parent_job = jobs.id
AND activechildjobs.id != jobs.id
AND activechildjobs.is_active = 'y'
WHERE jobs.id = 1
以下是不正确的结果。
job 1: 25 openings, 20 active openings
job 4: 13 openings, 0 active openings
job 6: 90 openings, 90 active openings
有多个孩子的工作会多次计算孩子。
解决方案
您可以使用条件聚合和 group byid_parent_job
来避免JOIN
导致记录重复的 s (因此计数不正确):
SELECT id_parent_job AS id,
SUM(num_openings) AS openings,
SUM(CASE WHEN is_active = 'y' THEN num_openings ELSE 0 END) AS active_openings
FROM jobs
GROUP BY id_parent_job
输出:
id openings active_openings
1 25 10
4 13 0
6 45 30
推荐阅读
- python - 使用连接池时的 SQLAlchemy KeyError
- python - 如何在python中记录鼠标移动?
- python - Groupby 和变换 Pandas
- ios - 在当前标签栏中获取另一个标签的视图控制器变量 - iOS - Swift
- java - 使用 VSCode 命令编译 C++ 时,它使用的是奇怪的
- vim - Vim:重新映射除视觉之外的所有模式
- thymeleaf - Thymeleaf 对 onmouseover 处理程序的限制
- python - 从 np.datetime64 转换为浮点年
- google-bigquery - 如何根据数组条件加入 2 个表包含
- vue.js - 在 Gridsome 中生成文档索引