SQL - 在没有密钥的情况下加入两个表

时间:2016-09-17 20:37:58

标签: sql oracle select join

给出两个表(count(Table1) <= count(Table2)):

表1:

record-1 
record-2 
... 
record-k

表2:

promo-1
promo-2
...
promo-j

是否可以将它们加入下表?即在Table1中为Table2中的某个条目分配每个条目,但Table1中的两个条目都不对应Table2中的相同条目。

结果:

record-1    promo-i1
record-2    promo-i2
...
record-n    promo-in

1 个答案:

答案 0 :(得分:5)

您可以使用rownum伪列创建假密钥,并根据以下内容加入:

SELECT t1.col1, t2.col2
FROM   (SELECT   col1, ROWNUM AS rn
        FROM     table1
        ORDER BY col1) t1
JOIN   (SELECT   col2, ROWNUM AS rn
        FROM     table2
        ORDER BY col2) t2 ON t1.rn = t2.rn

修改:
稍微“笨拙”,更加ANSI友好的方法是使用ROW_NUMBER()窗口函数:

SELECT t1.col1, t2.col2
FROM   (SELECT   col1, ROW_NUMBER() OVER (ORDER BY col1) AS rn
        FROM     table1) t1
JOIN   (SELECT   col2, ROW_NUMBER() OVER (ORDER BY col2) AS rn
        FROM     table2) t2 ON t1.rn = t2.rn