在sqlite3中组合两个表

时间:2012-01-01 22:59:05

标签: sql database sqlite

我在两个独立的sqlite3数据库中有两个表。数据类型相同,但模式略有不同。我希望它们是单个数据库中的单个表,具有与Table 2

相同的模式

表1

CREATE TABLE temp_entries (
    id INTEGER PRIMARY KEY, 
    sensor NUMERIC, 
    temp NUMERIC, 
    date NUMERIC);

表2

CREATE TABLE "restInterface_temp_entry" (
    "id" integer NOT NULL PRIMARY KEY,
    "dateTime" integer NOT NULL,
    "sensor" integer NOT NULL,
    "temp" integer NOT NULL
);

id在两个表之间不是唯一的。我想创建另一个与Table 2具有相同模式的表。我希望表1中条目的id从0开始,然后table 2中的条目从table 1的最后一个条目开始。

理想情况下,我只想将Table 1中的条目添加到Table 2并“重新索引”主键,使其与“dateTime”的升序顺序相同。

更新 :我现在让两个表都使用相同的模式,我通过在数据库中创建一个与Table 2具有相同模式的新表来完成此操作持有Table 1。我将数据复制到新表中,例如:

INSERT INTO restInterface_temp_entry(id,dateTime,sensor,temp)
   ...> select id,date,sensor,temp FROM temp_entries;

背景

我曾经将一堆temp_entries记录到csv文件中。我想将数据放入一种更易于使用的格式并选择sqlite3。我编写了一个程序,将所有条目拉出并将它们放入Table 1。我当时不确定我在做什么,并使用Table 2表示所有新条目。现在我想将它们全部组合起来,希望按升序保持id和日期。

2 个答案:

答案 0 :(得分:3)

想出来。

  • 打开当前数据库。
  • 附加到原始数据库

    ATTACH '/orig/db/location' as orig
    
  • 将记录从当前数据库移动到旧数据库,省略PK

    insert into orig.restInterface_temp_entry(dateTime,sensor,temp)
    ...> select dateTime,sensor,temp from main.restInterface_temp_entry;
    
  • 清除当前数据库表

    delete from main.restInterface_temp_entry where id > 0
    
  • 将原始数据库表中的所有更新记录复制回当前。

    insert into main.restInterface_temp_entry(id,dateTime,sensor,temp)
    ...> select id,dateTime,sensor,temp
    ...> from orig.restInterface_temp_entry;
    

答案 1 :(得分:-1)

我假设SQLLite支持INSERT INTO SELECT

INSERT INTO newtable (id, datetime, sensor, temp) 
    SELECT id, date, sensor, temp 
    FROM temp_entries
    ORDER BY id;
INSERT INTO newtable (id, datetime, sensor, temp) 
    SELECT "id", "dateTime", "sensor", "temp"
    FROM "restInterface_temp_entry"
    ORDER BY "id";

这应该可以解决问题。

相关问题