SQL(简单地)逐行连接两个表

时间:2017-04-10 23:52:18

标签: sql postgresql

我想逐行加入2个表,这意味着如果我有两个表A,B我希望:  A的第1行仅加入B的第1行  A的第2行仅加入B的第2行 等

所以,如果我有

table A
name

John
George
Nick
Legolas



table B
surname

Smith
Rogueman
Born
Yohazol


the result would be:

table C
name    surname


John    Smith
George  Rogueman
Nick    Born
Legolas Yohazol

提前致谢

2 个答案:

答案 0 :(得分:2)

像这样......

SELECT *
FROM (
  SELECT row_number() OVER (), *
  FROM tbl1
  -- ORDER BY id (or whatever you're ordering by)
) AS t1
INNER JOIN (
  SELECT row_number() OVER (), *
  FROM tbl2
  -- ORDER BY id (or whatever you're ordering by)
) AS t2
  USING (row_number);

答案 1 :(得分:0)

如果您没有id或任何匹配行的列,则可以使用ROW_NUMBER作为ID。

WITH cteA(rn, name) AS(
    SELECT
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn,
        name
    FROM tableA
),
cteB(rn, name) AS(
    SELECT
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn,
        name
    FROM tableB
)
SELECT
    a.name AS name,
    b.name AS surname
FROM cteA a
INNER JOIN cteB b
    ON b.rn = a.rn