获取匹配& oracle中的非匹配记录

时间:2015-12-30 07:37:43

标签: sql oracle oracle11g

表:学生

EmpId   Name   Course     Area    
--------------------------------
E001    John    Maths     USA
E001    John    Maths     LONDON
E001    John    English   LONDON
E001    John    English   GERMANY
E002    PETER   Maths     USA
E002    PETER   Maths     LONDON
E002    PETER   English   LONDON
E002    PETER   SCIENCE   GERMANY

表:主题

Course     Area
--------------------
Maths     USA
Maths     LONDON
English   GERMANY
ACCOUNTS  FRANCE 

我需要根据课程和区域比较这两个表,我需要与STUDENTCOURSE表中的非匹配记录匹配的记录。 感谢您的帮助和努力。

示例输出:

E001    John    Maths     USA
E001    John    Maths     LONDON
E001    John    English   LONDON
E001    John    English   GERMANY
null    null    ACCOUNTS  FRANCE
E002    PETER   Maths     USA
E002    PETER   Maths     LONDON
E002    PETER   English   LONDON
E002    PETER   SCIENCE   GERMANY
null    null    ACCOUNTS  FRANCE

谢谢

1 个答案:

答案 0 :(得分:0)

-- students with matching areas
select s.EmpId, s.name, a.course, a.area
  from student s
  inner join subject a
    on (a.course = s.course and a.area = s.area)
union all
-- areas without matching students
select s.EmpId, s.name, a.course, a.area
  from subject a
  left outer join student s
    on (s.course = a.course and s.area = a.area)
 where s.EmpId is null;

请你解释一下,为什么你期望行

E002    PETER   English   LONDON
E002    PETER   SCIENCE   GERMANY

在结果列表中?

为什么你期待这行

null    null    ACCOUNTS  FRANCE

两次?