在SQLite中如何在两个表之间复制数据?

10

我有两个表格,它们的列不同,就像这样:

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

table2
(
    _id,
    phone,
    name,
    address
)

我该如何将表格1中的“名称”和“地址”数据复制到表格2?

我的问题有两种情况:

  • 第一种情况:表格1和表格2在同一个数据库文件中。
  • 第二种情况:表格1在data1.db文件中,表格2在data2.db文件中。
1个回答

24

在 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呢? - TheOne
@Ramin:我的代码第一次插入所有的ID。如果您尝试插入已经存在的来自“table2”的ID,则会出现错误。因此,这两个更新语句将为所有现有ID复制非ID字段。 - Aaron Digulla
在我将主键ID重置为从1、2、3、...、n(从1开始的整数)时,第一段代码确实非常有用。 - wlwl2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接