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

时间:2009-10-13 12:03:33

标签: database sqlite

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

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

table2
(
    _id,
    phone,
    name,
    address
)

如何将数据'name','address'从table1复制到table2。

我的问题有两种情况:

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

1 个答案:

答案 0 :(得分:20)

在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结构”。