我有两个表格,它们的列不同,就像这样:
table1
(
_id,
title,
name,
number,
address
)
table2
(
_id,
phone,
name,
address
)
我该如何将表格1中的“名称”和“地址”数据复制到表格2?
我的问题有两种情况:
- 第一种情况:表格1和表格2在同一个数据库文件中。
- 第二种情况:表格1在data1.db文件中,表格2在data2.db文件中。
在 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结构”。