是否可以仅通过每个表中的第一个ID连接多个行的两个表?

时间:2013-02-22 22:19:00

标签: sql oracle

假设我有两个数据表:

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

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

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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