假设我创建了3个表并按如下方式填充它们:
CREATE TABLE t1(sn INT PRIMARY KEY, val TEXT);
INSERT INTO t1 (sn, val) VALUES (1,'Bobby');
INSERT INTO t1 (sn, val) VALUES (2,'Fred');
INSERT INTO t1 (sn, val) VALUES (3,'Ann');
t1看起来像这样
sn val
1 Bobby
2 Fred
3 Ann
和
CREATE TABLE t2(sn INT PRIMARY KEY, val INT);
INSERT INTO t2 (sn, val) VALUES (2,5);
INSERT INTO t2 (sn, val) VALUES (4,72);
INSERT INTO t2 (sn, val) VALUES (5,7);
t2将如此
sn val
2 5
4 72
5 7
和
CREATE TABLE t3(sn INT PRIMARY KEY, val TEXT);
INSERT INTO t3 (sn, val) VALUES (1,'A');
INSERT INTO t3 (sn, val) VALUES (5,'B');
INSERT INTO t3 (sn, val) VALUES (7,'C');
INSERT INTO t3 (sn, val) VALUES (9,'D');
t3将如此
sn val
1 A
5 B
7 C
9 D
现在我想创建一个名为“merged”的新表,并希望它看起来像这样
sn t1.val t2.val t3.val
1 Bobby A
2 Fred 5
3 Ann
4 72
5 7 B
7 C
9 D
我正在使用sqlite3,并尝试使用左连接和联合的组合,但我只能在不超过2个表的情况下使用它。我有很多这些表,并希望通过他们的主键加入所有表。您的建议将非常受欢迎,并期待您的回复。
答案 0 :(得分:0)
由于SQLite没有FULL OUTER JOIN
或RIGHT OUTER JOIN
支持,最简单的方法是使用INSERT OR REPLACE INTO
命令组合数据集,如下所示:
CREATE TABLE Result (sn INT PRIMARY KEY, val1 TEXT, val2 INT, val3 TEXT);
--
INSERT OR REPLACE INTO Result (sn, val1, val2, val3)
SELECT
sn
,val AS val1
,(SELECT val2 FROM Result AS R WHERE R.sn = sn) AS val2
,(SELECT val3 FROM Result AS R WHERE R.sn = sn) AS val3
FROM t1;
--
INSERT OR REPLACE INTO Result (sn, val1, val2, val3)
SELECT
sn
,(SELECT val1 FROM Result AS R WHERE R.sn = sn) AS val1
,val AS val2
,(SELECT val3 FROM Result AS R WHERE R.sn = sn) AS val3
FROM t2;
--
INSERT OR REPLACE INTO Result (sn, val1, val2, val3)
SELECT
sn
,(SELECT val1 FROM Result AS R WHERE R.sn = sn) AS val1
,(SELECT val2 FROM Result AS R WHERE R.sn = sn) AS val2
,val AS val3
FROM t3;
这是一个SQL Fiddle链接,显示它正常工作:http://www.sqlfiddle.com/#!7/ddfb7/2/0
答案 1 :(得分:0)
在子查询中使用UNION获取所有sn
值,然后为每个基表使用一堆左连接:
CREATE TABLE merged AS
SELECT tAll.sn,
t1.val,
t2.val,
t3.val
FROM (SELECT sn FROM t1
UNION
SELECT sn FROM t2
UNION
SELECT sn FROM t3) AS tAll
LEFT JOIN t1 ON tAll.sn = t1.sn
LEFT JOIN t2 ON tAll.sn = t2.sn
LEFT JOIN t3 ON tAll.sn = t3.sn