首页 > 解决方案 > 将表连接到自身时避免重复

问题描述

我确定答案已经存在,但我正在努力将足够相似的帖子应用于我的具体问题。请多多包涵。

我有一个使用 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

有多个孩子的工作会多次计算孩子。

标签: mysqljoin

解决方案


您可以使用条件聚合和 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

dbfiddle 上的演示


推荐阅读