左外连接IN运算符

时间:2014-06-30 17:50:50

标签: sql oracle outer-join

我正在使用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')

我知道工会会奏效。还有其他办法吗?

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

1 个答案:

答案 0 :(得分:2)

您需要生成所有可能的行,然后查看哪个匹配。这使用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;