使用SQLite合并数据

时间:2015-10-03 17:07:43

标签: sql sqlite

我正在尝试使用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中执行此操作?

1 个答案:

答案 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 ...