【问题标题】:Left Outer Join with IN operator使用 IN 运算符的左外连接
【发布时间】:2014-06-30 17:50:49
【问题描述】:

我正在使用 Oracle SQL。 以下是一些示例表:

People
PersonID   Name
1          Elmo
2          Oscar
3          Chris

Attribute
PersonID   Attribute
1          Happy
1          Muppet
1          Popular
2          Grouchy
2          Muppet
2          Popular
3          Programmer

我想要一份人员名单,我想知道我们是否知道他们是快乐的还是不高兴的。以下是我想要的输出:

Name       Mood
Elmo       Happy
Oscar      null (Happy)
Chris      null (Happy)

Elmo       null (Grouchy)
Oscar      Grouchy
Chris      null (Grouchy)

如果我使用这个查询,它不会返回我想要的额外的空结果行:

SELECT p.Name, a.Attribute
FROM People p
LEFT OUTER JOIN Attributes a
ON p.PersonID = a.PersonID AND a.Attribute IN ('Happy','Grouchy')

我知道工会会起作用。有没有其他方法可以做到这一点?

原谅我的懒惰,我修改了一个已经存在的问题。

【问题讨论】:

  • 你是说你想要一个NULL,但两者都不存在?
  • 您需要为“IN”条件下的每种情绪加入属性表。否则将无法返回 Elmo 快乐和 Elmo NULL
  • @GoatCO 是的,你是对的。

标签: sql oracle outer-join


【解决方案1】:

您需要生成所有可能的行,然后查看哪个匹配。这使用了cross joinleft join

select p.name,
       (case when pm.mood is not null then pm.mood
             else 'NULL (' || m.mood || ')'
        end) as mood
from (select 'Happy' as mood from dual union all
      select 'Grouchy' from dual
     ) m cross join
     (select distinct p.name from people
     ) p left outer join
     People pm
     on pm.name = p.name and pm.mood = p.mood
order by m.mood, p.name;

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多