简体   繁体   English

左外与IN运算符联接

[英]Left Outer Join with IN operator

I am using Oracle SQL. 我正在使用Oracle SQL。 Here are some example tables: 以下是一些示例表:

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

I want a list of people and I want to know whether we have knowledge of them being happy or grouchy. 我想要一个人的名单,我想知道我们是否知道他们的幸福或脾气暴躁。 The following is the output I want: 以下是我想要的输出:

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

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

If I use this query, it will not return the additional null result rows that I want: 如果使用此查询,它将不会返回我想要的其他空结果行:

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

I know union would work. 我知道工会会奏效。 Is there any other way to do this ? 还有其他方法吗?

Pardon my laziness, I modified an already existing question. 请原谅我的懒惰,我修改了一个已经存在的问题。

You need to generate all the possible rows and then see which match. 您需要生成所有可能的行,然后查看匹配的行。 This uses a cross join and left join : 这使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM