0

假设我有两个数据表:

Table A
ID    Colors
--    ------
1     Blue
1     Green
1     Red

Table B
ID    States
--    ------
1     MD
1     VA
1     WY
1     CA

是否可以加入这些表以便我得到以下而不是 12 行?

ID    Colors    States
--    ------    ------
1     Blue      MD
1     Green     VA
1     Red       WY
1               CA

颜色和状态列之间没有关联,并且列的顺序无关紧要。(例如,蓝色可以在 MD、VA、WY 或 CA 旁边)每个 ID 每列(颜色或州)中的项目数不相等。

谢谢。

4

2 回答 2

1

您可以通过使用row_number()创建一个假连接列来做到这一点:

select coalesce(a.id, b.id) as id, a.colors, b.states
from (select a.*, row_number() over (order by id) as seqnum
      from a
     ) a full outer join
     (select b.*, row_number() over (order by id) as seqnum
      from b
     ) b
     on b.seqnum = a.seqnum

实际上,在 Oracle 中,您也可以只使用rownum

select coalesce(a.id, b.id) as id, a.colors, b.states
from (select a.*, rownum as seqnum
      from a
     ) a full outer join
     (select b.*, rownum as seqnum
      from b
     ) b
     on b.seqnum = a.seqnum
于 2013-02-22T22:21:06.580 回答
0

您还可以像这样使用 CTE(通用表表达式):

WITH TableA (ID, Color) AS
(
    SELECT "ID", Color 
    FROM DatabaseName.TableA
)
, Joined AS (
    SELECT 
        a.ID AS "AID",
        a.Color
        b.ID AS "BID", 
        b."State"
    FROM, 
        TableA AS a
            RIGHT OUTER JOIN DatabaseName.TableB AS b ON a.ID = b.ID
)

SELECT
    AID,
    Color,
    State
FROM
    Joined
于 2013-02-22T22:34:59.350 回答