【问题标题】:Rewrite Join which introduces duplicate rows without DISTINCTRewrite Join 引入了没有 DISTINCT 的重复行
【发布时间】:2020-07-08 16:46:56
【问题描述】:

我有一个查询,我需要在 JOIN 与表 CAREER_GOALS_T 之后获得不同的 PLANS_T.ID,该表可以列出每个 PLANS_T.ID 的多个条目。因此,我的结果中出现了重复的 PLAN ID。

以下是简化版。许多其他领域也正在被选中。我不想将DISTINCT 放在我的PLANS_T.ID 上,因为我的查询还应该返回所有PLAN ID = NULL 的情况。如果我的标准包括careergoals.goal_id in (..),则需要DISTINCT,但有时我没有这些标准。我不想在我的代码中打开/关闭DISTINCT,我希望对所有情况进行一致的查询。

我正在寻找的是没有DISTINCT 的其他解决方案,它可以让我为任何匹配的加入结果获得唯一的PLANS_T.ID;否则为NULL。

    select
        plans.ID 
  
    from
        PLANS_T plans 
    inner join
        CAREER_GOALS_T careergoals
            on plans.ID=careergoals.PLAN_ID 
   where
     careergoals.goal_id in (39, 41, 42);

SQLFiddle http://sqlfiddle.com/#!4/30f59/4

【问题讨论】:

  • 添加示例数据有助于其他人更好地理解您的问题。
  • select distinct where goal_id in (39, 41, 42) union all select where id is null?
  • 用您正在使用的数据库标记您的问题。样本数据和期望的结果会有所帮助。
  • 完成,Oracle 19c。
  • 轻松为您提供帮助:minimal reproducible example.

标签: sql oracle


【解决方案1】:

正如@a_horse_with_no_name 所建议的,我认为您只需要exists

select p.id
from plans_t p
where p.id is null 
or exists (select 1 
           from career_goals_t c
           where p.id=c.plan_id 
           and goal_id in (39, 41, 42));

【讨论】:

  • 我在 SqlFiddle 中运行这个,语法错误:sqlfiddle.com/#!4/30f59/26
  • 在本例中,预期输出为“2,3”。如果删除 Join/Where,预期输出为每个“1,2,null, null, null, 3, 4”。在任何情况下我都不想要重复的非 NULL 计划。
  • 哦,在这种情况下,使用上面的。如果你不想要空值,你可以去掉p.id is null
【解决方案2】:

这对你有用吗?

select
    plans.ID  
from
    PLANS_T plans 
where plans.ID in (
  select plan_id from career_goals_t careergoals where
 careergoals.goal_id in (39, 41, 42)
)

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多