2009-10-13 96 views
8

我有两个表,不同的列是这样的:如何在SQLite中的两个表之间复制数据?

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

table2 
(
    _id, 
    phone, 
    name, 
    address 
) 

如何从表1的数据复制“姓名”,“地址”,以表2。

我的问题有两个情况:

  • 第一:表1,表2中的同一个数据库文件
  • 二:表1中data1.db文件,表2中data2.db文件

回答

20

复制在SQL就像这样:

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

如果列的值都是一样的,你需要插入和更新

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

+0

为什么不直接在第一次插入ID? – TheOne 2013-01-30 15:57:26

+0

@Ramin:我的代码第一次插入所有的ID。如果您尝试从已存在的'table2'中插入id,则会出现错误。所以这两个更新语句将复制所有现有ID的非ID字段。 – 2013-01-30 16:48:49

相关问题