我正在尝试将SQLite数据库中的三个表组合成一个新的组合表。这三个表具有相同的列名,但第三个表缺少其中一个列。以下是我尝试这样做的方法:
CREATE TABLE cobmined
AS
SELECT col1, col2, col3
FROM
(
SELECT col1, col2, col3 from table1
UNION ALL
SELECT col1, col2, col3 from table2
UNION ALL
SELECT col1, col2 from table3
) s
;
仅在前两个表上执行此操作时,当添加第三个表时,我收到消息:
SELECTs to the left and right of UNION do not have the same number of result columns
有没有办法让SQL忽略丢失的列,如果需要可以留下NULL?
答案 0 :(得分:2)
将NULL值添加到第三个表
CREATE TABLE cobmined
AS
SELECT col1, col2, col3
FROM
(
SELECT col1, col2, col3 from table1
UNION ALL
SELECT col1, col2, col3 from table2
UNION ALL
SELECT col1, col2, null from table3
) s
;
此外,不需要子查询
CREATE TABLE cobmined
AS
SELECT col1, col2, col3 from table1
UNION ALL
SELECT col1, col2, col3 from table2
UNION ALL
SELECT col1, col2, null from table3
答案 1 :(得分:0)
我想请注意,您不需要子查询:
CREATE TABLE combined AS
SELECT col1, col2, col3 from table1
UNION ALL
SELECT col1, col2, col3 from table2
UNION ALL
SELECT col1, col2, NULL from table3;
此外,您可能会发现视图更适合您的目的而非实际表格。