【问题标题】:how to merge two sqlite3 databases with same schema having primary key with auto increment如何合并两个具有相同模式的sqlite3数据库,主键具有自动增量
【发布时间】:2014-11-28 05:56:09
【问题描述】:

我想将两个或多个sqlite databasessame schema 合并,其中每个数据库中的一列具有自动增量的主键。

例如: 我有两个数据库: student1.db

idxnameage

  1. abc 15
  2. 定义 16
  3. 吉15
  4. jkl 16

另一个数据库:student2.db

idxnameage

  1. mno 15
  2. pqr 16
  3. stu 16
  4. vwx 15

我已将idx 列添加为primary keyauto increment

现在我想将student2.dbstudent1.db 合并,而不创建temp db。 合并后的一些内容student1.db 应该如下所示。

student1.db after merge

idxname`年龄

  1. abc 15
  2. 定义 16
  3. 吉15
  4. jkl 16
  5. mno 15
  6. pqr 16
  7. stu 16
  8. vwx 15

我知道我们可以使用附加。但是,如果其中一列是 primary key 并具有自动增量,则不会合并。合并后,我希望 idx 列以增量方式附加 existing idx 列。

下面是.schema for student1 and student2 db

sqlite3 student1.db

sqlite>.schema

CREATE TABLE student (

 'idx' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,

 'name' CHAR(32) NOT NULL,

 'age' INTEGER NOT NULL default 0,

  UNIQUE (name)

  );


 sqlite> select * from student;

  1|abc|15

  2|def|16

  3|ghi|15

  4|jkl|16

  sqlite>

  sqlite3 student2.db

  SQLite version 3.6.20

  Enter ".help" for instructions

  Enter SQL statements terminated with a ";"

  sqlite> .schema

  CREATE TABLE student (

  'idx' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,

  'name' CHAR(32) NOT NULL,

  'age' INTEGER NOT NULL default 0,

   UNIQUE (name)

  );

  sqlite> select * from student;

  1|mno|15

  2|pqr|16

  3|stu|15

  4|vwx|16

  sqlite>



 This is what I used to merge two database. 

 attach './student2.db' as toMerge;

 BEGIN;

  insert or ignore into student

  select * from toMerge.student;

  COMMIT;

  detach database toMerge;

请告诉我如何使用主键合并两个数据库 非常感谢您在这方面的帮助。

提前致谢。

【问题讨论】:

    标签: mysql database sqlite


    【解决方案1】:

    当 INTEGER PRIMARY KEY 列的插入值为 NULL 时,SQLite 会创建新 ID。

    所以你必须复制所有列除了 ID:

    INSERT INTO student(name, age)
    SELECT name, age
    FROM toMerge.student;
    

    【讨论】:

    • 感谢您的回复。我按照您建议的步骤进行操作,合并两个数据库对我有用。
    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2016-04-02
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多