2015-12-02 120 views
1

更新單個指定值I具有定義爲兩個SQLite的表AB從另一個表中的SQLite

CREATE TABLE A (orig_cat INTEGER, type INTEGER,gv_ID INTEGER); 
INSERT INTO A (orig_cat,type) VALUES (1,1); 
INSERT INTO A (orig_cat,type) VALUES (2,2); 
INSERT INTO A (orig_cat,type) VALUES (3,2); 
INSERT INTO A (orig_cat,type) VALUES (4,2); 
INSERT INTO A (orig_cat,type) VALUES (1,3); 
INSERT INTO A (orig_cat,type) VALUES (2,3); 
INSERT INTO A (orig_cat,type) VALUES (3,3); 
UPDATE A SET gv_ID=rowid+99; 

CREATE TABLE B (col_t INTEGER, orig_cat INTEGER, part INTEGER); 
INSERT INTO B VALUES (1,1,1); 
INSERT INTO B VALUES (3,1,2); 
INSERT INTO B VALUES (2,2,1); 
INSERT INTO B VALUES (1,2,2); 
INSERT INTO B VALUES (3,3,1); 
INSERT INTO B VALUES (4,3,2); 

我想更新並設置/更換值在表B的列col_t中,其中part=2具有表的列gv_ID的選定值。所選擇的值I可以用SELECT命令得到:

SELECT gv_ID 
FROM (SELECT * FROM B where part=2) AS B_sub 
JOIN (SELECT * FROM A WHERE type=3) AS A_sub 
    ON B_sub.orig_cat=A_sub.orig_cat; 

如何可以使用使得col_t在第2,3行和圖5(= 1,2,3)的值獲得與值104105106替換(這是由選擇返回)?

回答

1

你可以使用相關子查詢:

UPDATE B 
SET col_t = (SELECT gv_ID FROM A WHERE A.orig_cat = B.orig_cat AND A.type = 3) 
WHERE B."part" = 2; 

SqlFiddleDemo

我認爲對A.orig_catA.typeUNIQUE