2012-06-06 266 views
4

我想更新SQLite表中列中的選定值。我只想更新符合條件的維護中的單元格,並且必須將單元格更新爲從子表中取得的單個值。正確的SQLite語法 - UPDATE SELECT與WHERE EXISTS

我試過以下語法,但我只得到單個單元格更新。我也嘗試了所有單元格都更新到子表格的第一個選定值的替代方案。

UPDATE maintable 
SET value=(SELECT subtable.value FROM maintable, subtable 
WHERE maintable.key1=subtable.key1 AND maintable.key2=subtable.key2) 
WHERE EXISTS (SELECT subtable.value FROM maintable, subtable 
WHERE maintable.key1=subtable.key1 AND maintable.key2=subtable.key2) 

什麼是適當的語法?

回答

3

您需要使用INSERT或REPLACE語句,像下面這樣:

假設maintable有4列:鍵,COL2,COL3,COL4
並要更新與子表的匹配值COL3

INSERT OR REPLACE INTO maintable 
SELECT maintable.key, maintable.col2, subtable.value, maintable.col4 
FROM maintable 
JOIN subtable ON subtable.key = maintable.key 
+0

好的答案,但是你不需要**來做'INSERT OR REPLACE'。我發現了另一個答案:)另外INSERT或REPLACE會要求你有主鍵的所有字段的權利? – Jess

+0

對我來說就像一個魅力... –

11

您可以用update select來做到這一點,但是一次只能做一個字段。如果Sqlite支持在更新語句中進行連接,但它不會。

這是一個相關的SO問題,How do I UPDATE from a SELECT in SQL Server?,但是用於SQL Server。那裏有類似的答案。

sqlite> create table t1 (id int, value1 int); 
sqlite> insert into t1 values (1,0),(2,0); 
sqlite> select * from t1; 
1|0 
2|0 
sqlite> create table t2 (id int, value2 int); 
sqlite> insert into t2 values (1,101),(2,102); 
sqlite> update t1 set value1 = (select value2 from t2 where t2.id = t1.id) where t1.value1 = 0; 
sqlite> select * from t1; 
1|101 
2|102