我正在尝试使用cli找到一种在sqlite数据库中合并数据的方法。
示例:
TABLE1 with col1(keys)& col2(values1)
╔══════╦═════════╗
║ col1 ║ values1 ║
╠══════╬═════════╣
║ 1234 ║ 456 ║
║ 1235 ║ 789 ║
╚══════╩═════════╝
TABLE2 with col1(keys)& col2(values2)
╔══════╦═════════╗
║ col1 ║ values2 ║
╠══════╬═════════╣
║ 1233 ║ 235 ║
║ 1234 ║ 457 ║
║ 1235 ║ 790 ║
╚══════╩═════════╝
目标: 表3带有col1(键)& col2(values1)& col3(values2)
╔══════╦═════════╦═════════╗
║ col1 ║ values1 ║ values2 ║
╠══════╬═════════╬═════════╣
║ 1233 ║ NULL ║ 235 ║
║ 1234 ║ 456 ║ 457 ║
║ 1235 ║ 789 ║ 790 ║
╚══════╩═════════╩═════════╝
我如何在SQL中执行此操作?
答案 0 :(得分:2)
您可以使用CREATE TABLE AS
:
<强> SqlFiddleDemo 强>
数据:
CREATE TABLE TABLE1(col1 INT, values1 INT);
INSERT INTO TABLE1
VALUES (1234,456), (1235,789);
CREATE TABLE TABLE2(col1 INT, values2 INT);
INSERT INTO TABLE2
VALUES (1233,235), (1234,457), (1235,790);
主要查询:
CREATE TABLE TABLE3
AS
SELECT col1, MAX(values1) AS values1, MAX(values2) AS values2
FROM(
SELECT t1.col1 AS col1, t1.values1 AS values1, t2.values2 AS values2
FROM TABLE1 t1
LEFT JOIN TABLE2 t2
ON t1.col1 = t2.col1
UNION ALL
SELECT t2.col1 AS col1, t1.values1 AS values1, t2.values2 AS values2
FROM TABLE2 t2
LEFT JOIN TABLE1 t1
ON t1.col1 = t2.col1) as tab
GROUP BY col1;
当SQLite支持FULL OUTER JOIN
时可能会容易得多,因此不需要使用UNION ALL
子查询和ORACLE
:
<强> SqlFiddleDemo2 强>
CREATE TABLE TABLE3
AS
SELECT
COALESCE(t1.col1, t2.col1) AS col1,
t1.values1 AS values1,
t2.values2 AS values2
FROM TABLE1 t1
FULL JOIN TABLE2 t2
ON t1.col1 = t2.col1;
或SQL SERVER
:
<强> SqlFiddleDemo3 强>
SELECT
COALESCE(t1.col1, t2.col1) AS col1,
t1.values1 AS values1,
t2.values2 AS values2
INTO TABLE3
FROM TABLE1 t1
FULL JOIN TABLE2 t2
ON t1.col1 = t2.col1;
警告:的
创建初始表后,您必须INSERT
使用:
<强> SqlFiddleDemo4 强>
INSERT INTO TABLE3(col1,values1, values2)
SELECT ...