2010-11-27 183 views
45

SQLITEsqlite將數據從一個表複製到另一個表

我有2個表「Source」和「Destination」具有相同的字段。 ID和COUNTRY,儘管它們都有其他領域也不相同。

我需要的Source.Country值複製到Destination.Country其中加入是ID

對於我的生活,我不能讓sqlite的做到這一點。

在SQL Server等這是一個超級簡單的任務。

想法?

+1

更新目的地 SET國家=(選擇國家從源其中id = Destination.id) WHERE EXISTS(從源選擇1其中id = Destination.id); – 2010-11-27 12:04:45

+0

會有點像這樣嗎? http://stackoverflow.com/questions/2717590/sqlite-upsert-on-duplicate-key-update – Tom 2010-11-27 11:20:46

回答

100
INSERT INTO Destination SELECT * FROM Source; 

查看SQL As Understood By SQLite: INSERT的正式定義。

+1

贏得;噸工作,因爲我需要加入ID字段,只更新一個字段(國家)。 – 2010-11-27 11:17:23

+4

您可以在`SELECT`查詢中輕鬆修改表達式以匹配您的實際表格模式。 – joschi 2010-11-27 12:17:47

1

如果您正在複製這樣的數據,那可能意味着您的數據模型沒有完全標準化,對嗎?是否可以創建一個國家/地區列表並加入更多聯盟?

而不是JOIN你也可以使用虛擬表,所以你不必改變系統中的查詢。

4

如果已經存在兩個表中的數據,你要根據一些條件來更新表列的值,然後用這個

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id) 
1

我一直在摔跤這個問題,而且我知道有其他的選擇,但我得出的結論是最安全的模式是:

create table destination_old as select * from destination; 

drop table destination; 

create table destination as select 
d.*, s.country 
from destination_old d left join source s 
on d.id=s.id; 

它是安全的,因爲你有destination副本你改變它。我懷疑帶有連接的更新語句不包含在SQLite中,因爲它們功能強大但有點風險。

使用上面的模式,最終得到兩個country字段。如果source中的country字段爲空,則可以通過明確聲明要從destination_old中檢索的所有列以及可能使用​​3210檢索destination_old中的值來避免這種情況。因此,例如:

create table destination as select 
d.field1, d.field2,...,coalesce(s.country,d.country) country 
from destination_old d left join source s 
on d.id=s.id; 
相關問題