如何使用没有公共列的sql连接两个表

时间:2015-08-18 19:39:04

标签: sql-server

示例:

表1:

Column1           Column2
-----------       -------------
A                 1
B                 2
D                 3
E                 4

表2:

Column3           Column4
-----------       -------------
A                 7
E                 9
Z                 5

预期产出:

Column1           Column2             Column3            Column4
-----------       -------------       -------------      -------------
A                 1                   A                  7
B                 2                   E                  9
D                 3                   Z                  5
E                 4                   NULL               NULL

我想要输出如图所示。

如果有两个表的列为Column1,Coumn2和Column3,Column4 然后预期的输出应该是Column1,Column2,Column3,Column4,没有任何连接。它应该只是Table2在Table1的右侧。如果行数不匹配,则Null值将占用空间。

3 个答案:

答案 0 :(得分:6)

您可以使用ROW_NUMBER窗口函数创建一个可用于将两个表连接在一起的计算字段:

SELECT t1.Column1, t1.Column2, t2.Column3, t2.Column4
FROM (
   SELECT Column1, Column2,
          ROW_NUMBER() OVER (ORDER BY Column1) AS rn
   FROM Table1) AS t1
FULL OUTER JOIN  (
   SELECT Column3, Column4,
          ROW_NUMBER() OVER (ORDER BY Column3) AS rn
   FROM Table2) AS t2
ON t1.rn = t2.rn

如果FULL OUTER JOINTable1有更多行,则需要Table2

答案 1 :(得分:1)

这样可行: -

SELECT Column1, Column2, Column3, Column4 FROM 
(SELECT ROW_NUMBER() OVER(ORDER BY Column1) row, Table1.*
FROM Table1) t1
FULL OUTER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Column3) row, Table2.*
           FROM Table2) t2
ON t1.row = t2.row

SQLFIDDLE

答案 2 :(得分:0)

或者,您也可以执行left join而不是full outer join

SELECT Column1
    ,Column2
    ,t.Column3
    ,t.Column4
FROM (
    SELECT ROW_NUMBER() OVER (
            ORDER BY Column1
            ) rn
        ,Table1.*
    FROM Table1
    ) t1
LEFT JOIN (
    SELECT ROW_NUMBER() OVER (
            ORDER BY Column3
            ) AS rn
        ,t2.*
    FROM Table2 t2
    ) t ON t1.rn = t.rn;

SQL Fiddle Demo

注意:当然,如果您在TableA中有更多记录,这只会起作用。