SQL Query没有重复

时间:2013-11-23 07:41:08

标签: sql

我有3张这样的表:

姓名:

ID(K)   Name
--------------
1        n1
2        n2

工作:

ID      Job
------------
1        j1
1        j2

电话:

ID      Phone
--------------
1        p1
1        p2
1        p3
1        p4

我正在使用LEFT OUTER JOIN进行SELECT:

SELECT Names.Name, Jobs.Job, Phones.Phone
FROM
   Names LEFT OUTER JOIN Jobs ON Jobs.ID = Names.ID 
   LEFT OUTER JOIN Phones ON Phones.ID = Names.ID

并返回:

n1   j1   p1
n1   j1   p2
n1   j1   p3
n1   j1   p4
n1   j2   p1
n1   j2   p2
n1   j2   p3
n1   j2   p4
n2  null null

但我需要这个结果:

n1   j1   p1
n1   j2   p2
n1  null  p3
n1  null  p4
n2  null null

解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您没有指定哪个RDBMS,但此查询至少适用于SQL Server,PostgreSQL和Oracle。可能有一个更聪明的分析功能来做到这一点,但它现在逃脱了我。

WITH pjobs AS (
  SELECT id, job, 
  ROW_NUMBER() OVER(PARTITION BY id ORDER BY   job) rn FROM jobs
), pphones AS (
  SELECT id, phone, 
  ROW_NUMBER() OVER(PARTITION BY id ORDER BY phone) rn FROM phones
)
SELECT name, job, phone
FROM pjobs FULL JOIN pphones ON pjobs.rn = pphones.rn AND pjobs.id = pphones.id
RIGHT JOIN names ON names.id = pjobs.id OR names.id = pphones.id

An SQLfiddle to test with