多对多与最少重复的行连接

时间:2014-10-13 09:55:12

标签: sql oracle join

假设我有两张桌子。每个表都有一个ID列。每个表中的多个行可能具有相同的ID。我需要在ID上加入表格,只选择每个表格中的每个记录一次。表之间存在多对多的关系。使用Oracle数据库。

假设我们有两张桌子。

表1:

ID | Office Address
-------------------
1  | A Street
1  | B Street
2  | C street
3  | D Street

表2:

ID | Company Name
------------------
1  | Toys Limited
1  | Toys Incorporated
1  | Toys Unlimited
2  | Best Cakes
4  | Best Boxes

我想得到的是:

ID | Company Address              | Company Name
----------------------------------------------
1  | A Street                     | Toys Limited
1  | B Street                     | Toys Incorporated
1  | Null (some value acceptable) | Toys Unlimited
2  | C Street                     | Best Cakes
3  | D Street                     | Null
4  | Null                         | Best Boxes

我需要在10个不同的表中跨越这个查询,总共有300列,所以不必指定每一列就好了。

1 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT COALESCE(t1.id, t2.id) AS ID, t1.Office_Address, t2.Company_Name
FROM (
  SELECT t1.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS rn
  FROM Table1 t1
) t1
FULL OUTER JOIN (
  SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS rn
  FROM Table2 t2
) t2 ON t1.id = t2.id AND t1.rn = t2.rn
ORDER BY ID

SQL Fiddle

上测试