1

我有以下表格

table 2 with a fk to table 1
table 3 with a fk to table 1

在表 2 中,我有两行链接到表 1 在表 3 中,我有一行链接到表 1

我正在尝试制作一张具有

| table1 pk  | table 2 pk | null |
| table1 pk  | table 2 pk | null |
| table1 pk  | null | table 3 pk |

但是,当我尝试以下操作时,我得到

select tab1.id, tab2.id, tab3.id
from table1 tab1 
left join tab2 on tab1.id = tab2.tab1_id
left join tab3 on tab1.id = tab3.tab1_id

给出这张表

| table1 pk  | table 2 pk | table 3 pk |
| table1 pk  | table 2 pk | table 3 pk |

有人可以帮忙解决这个 SQL 吗?

提前致谢

编辑

我想我可能把这简化了一点。理想的输出是

| table1 pk  | table 2 pk |
| table1 pk  | table 3 pk |
| table1 pk  | table 3 pk |

一旦我得到这个加入工作,它将被添加到另一个大规模查询中......

4

3 回答 3

1

您可以对联合的结果使用连接:

SELECT
  t1.table1pk,
  t23.table2pk,
  t23.table3pk
FROM table1 t1
INNER JOIN
(
  SELECT table2pk, NULL AS table3pk, table1fk
  FROM table2

  UNION ALL

  SELECT NULL AS table2pk, table3pk, table1fk
  FROM table3
) t23
ON t1.table1pk = t23.table1fk
;

或者您可以使用两个连接结果的联合:

SELECT
  t1.table1pk,
  t2.table2pk,
  NULL AS table3pk
FROM table1 t1
INNER JOIN table2 t2
ON t1.table1pk = t2.table1fk

UNION ALL

SELECT
  t1.table1pk,
  NULL AS table2pk,
  t3.table3pk
FROM table1 t1
INNER JOIN table3 t3
ON t1.table1pk = t3.table1fk
;

这两种方法都可以适应生成所需输出的两列版本:

  • 加入工会:

    SELECT
      t1.table1pk,
      t23.otherpk
    FROM table1 t1
    INNER JOIN
    (
      SELECT table2pk AS otherpk, table1fk
      FROM table2
    
      UNION ALL
    
      SELECT table3pk AS otherpk, table1fk
      FROM table3
    ) t23
    ON t1.table1pk = t23.table1fk
    ;
    
  • 联合联合:

    SELECT
      t1.table1pk,
      t2.table2pk AS otherpk
    FROM table1 t1
    INNER JOIN table2 t2
    ON t1.table1pk = t2.table1fk
    
    UNION ALL
    
    SELECT
      t1.table1pk,
      t3.table3pk AS otherpk
    FROM table1 t1
    INNER JOIN table3 t3
    ON t1.table1pk = t3.table1fk
    ;
    
于 2013-10-31T07:41:04.120 回答
1

一种不寻常的解决方案是

select coalesce(t2.tab1_id, t3.tab1_id) pk,
   t2.pk, t3.pk
from table2 t2 
   full join table3 t3
       on t3.tab1_id = t2.tab1_id
where exists (select * from table1
              where pk in (t2.tab1_id, t3.tab1_id)

注意(编辑)正如 Andriy M 在评论中所指出的,where 子句仅从 table2 和 table3 中删除 FK 在 table1 中不存在的行,如果 FK 约束已正确应用于 table2 和 table3,则不会存在。

于 2013-10-30T13:09:48.253 回答
1

我在这里没有看到任何疯狂的东西

WITH TAB1
    AS (SELECT 1 AS ID FROM DUAL
        UNION ALL
        SELECT 2 AS ID FROM DUAL
        UNION ALL
        SELECT 3 AS ID FROM DUAL),
    TAB2
    AS (SELECT 1 AS TAB1_ID, 'A' AS ID FROM DUAL
        UNION ALL
        SELECT 2 AS TAB1_ID, 'B' AS ID
        FROM DUAL),
    TAB3
    AS (SELECT 3 AS TAB1_ID, 'C' AS ID
        FROM DUAL)
SELECT
      TAB1.ID,
      COALESCE ( TAB2.ID,
               TAB3.ID )
FROM
      TAB1
      LEFT JOIN TAB2
          ON TAB1.ID = TAB2.TAB1_ID
      LEFT JOIN TAB3
          ON TAB1.ID = TAB3.TAB1_ID;

1   A   
2   B   
3   C
于 2013-10-30T13:12:08.663 回答