开发者

Three-way full outer join in SQLite

开发者 https://www.devze.com 2022-12-31 20:37 出处:网络
I have three tables with a common key field, and I need to join them on this key. Given SQLite doesn\'t have full outer or right joins, I\'ve used the full outer join without right join technique on W

I have three tables with a common key field, and I need to join them on this key. Given SQLite doesn't have full outer or right joins, I've used the full outer join without right join technique on Wikipedia with much success.

But I'm curious, how would one use this technique to join three tables by a common key? What 开发者_StackOverfloware the efficiency impacts of this (the current query takes about ten minutes)?

Thanks!


You can create temporary table with all keys with UNION SELECT. And then LEFT JOIN to this temporary table other tables;

    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);


If people stumble across this later, I ultimately tried using temporary tables after the first join, and then joined on this temporary table. It became a hassle, so I ultimately switched to PostgreSQL (which has full outer joins).

0

精彩评论

暂无评论...
验证码 换一张
取 消