【问题标题】:How to copy data between two tables in SQLite?如何在 SQLite 中的两个表之间复制数据?
【发布时间】:2015-11-24 03:36:48
【问题描述】:

我有两个不同列的表,如下所示:

table1
(
    _id,
    title,
    name,
    number,
    address
)

table2
(
    _id,
    phone,
    name,
    address
)

如何将数据“名称”、“地址”从 table1 复制到 table2。

而我的问题有两种情况:

  • 首先:table1、table2在同一个数据库文件中
  • 二:data1.db文件中的table1,data2.db文件中的table2

【问题讨论】:

    标签: database sqlite


    【解决方案1】:

    在 SQL 中复制的工作方式如下:

    insert into table2 (name, address)
    select name, address
    from table1
    

    如果id_列的值相同,则需要插入更新

    insert into table2 (name, address)
    select name, address
    from table1 t1
    where not exists (select * from table2 t2 where t1._id = t2._id)
    ;
    update table2 t2 name = (select name from table1 t2 where t1._id = t2._id)
    ;
    update table2 t2 address = (select address from table1 t2 where t1._id = t2._id)
    

    如果您需要在数据库之间复制列,请先将它们导出到一个文件中(使用您喜欢的任何格式,例如 CSV),然后手动将该文件合并到第二个数据库中,因为您无法编写 SQL说“使用这些 sqlite 结构”。

    【讨论】:

    • 为什么不第一次插入ID?
    • @Ramin:我的代码第一次插入了所有的 id。如果您尝试从 table2 插入已经存在的 id,您将收到错误消息。所以这两个更新语句将复制所有现有 id 的非 id 字段。
    • 在我重置我的主键 ID(从随机数到 1,2,3,...,n(从 1 开始的整数))的情况下,第一段代码真的很有帮助.
    猜你喜欢
    • 1970-01-01
    • 2017-02-12
    • 2019-03-27
    • 2013-01-25
    • 1970-01-01
    • 2012-04-03
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多