2010-05-26 65 views

回答

-3

如果人們後來偶然發現,我最終嘗試在第一次加入後使用臨時表,然後加入到這個臨時表中。這成了一件麻煩事,所以我最終轉向了PostgreSQL(它有完整的外連接)。

+2

更改數據庫引擎不是答案。 – peterdemin 2012-10-17 13:51:38

1

您可以使用UNION SELECT創建包含所有鍵的臨時表。然後LEFT JOIN將這張臨時表的其他表格;

CREATE TABLE a (
     tc INTEGER NOT NULL PRIMARY KEY, 
     v INTEGER 
    ); 
    CREATE TABLE b (
     tc NOT NULL PRIMARY KEY, 
     v INTEGER 
    ); 
    CREATE TABLE c (
     tc NOT NULL PRIMARY KEY, 
     v INTEGER 
    ); 
    INSERT INTO a (tc, v) VALUES(1, 10); 
    INSERT INTO a (tc, v) VALUES(2, 20); 
    INSERT INTO a (tc, v) VALUES(4, 40); 

    INSERT INTO b (tc, v) VALUES(1, 100); 
    INSERT INTO b (tc, v) VALUES(3, 300); 
    INSERT INTO b (tc, v) VALUES(5, 500); 

    INSERT INTO c (tc, v) VALUES(1, 1000); 
    INSERT INTO c (tc, v) VALUES(3, 3000); 
    INSERT INTO c (tc, v) VALUES(7, 7000); 

    CREATE TEMP TABLE keys 
    AS 
    SELECT tc as tc FROM a 
    UNION 
    SELECT tc as tc FROM b 
    UNION 
    SELECT tc as tc FROM c; 

    SELECT k.tc, a.v, b.v, c.v 
     FROM keys as k 
LEFT JOIN a ON (k.tc = a.tc) 
LEFT JOIN b ON (k.tc = b.tc) 
LEFT JOIN c ON (k.tc = c.tc);