2016-11-09 39 views
0

我想用另一個表中的值取代sqlite表,但條件是在關鍵字段中匹配值,但不知道如何去做。如何在sqlite中執行相關的查詢操作

Postgres裏我可以使用「相關查詢」,如下

drop table if exists zzzz_tab_1; 
drop table if exists zzzz_tab_2; 
drop table if exists zzzz_tab_3; 

create table zzzz_tab_1 (nr int , x_names varchar(20)); 
create table zzzz_tab_2 (nr int , x_age int); 
create table zzzz_tab_3 (nr int , x_names varchar(20), x_age int); 

INSERT INTO zzzz_tab_1 (nr, x_names) VALUES (1, 'AB'); 
INSERT INTO zzzz_tab_1 (nr, x_names) VALUES (2, 'BA'); 
INSERT INTO zzzz_tab_1 (nr, x_names) VALUES (3, 'CD'); 

INSERT INTO zzzz_tab_2 (nr, x_age) VALUES (1, 10); 
INSERT INTO zzzz_tab_2 (nr, x_age) VALUES (3, 20); 

-- add values 

-- add nr from zzzz_tab_1 
insert into zzzz_tab_3 (nr) select nr from zzzz_tab_1; 
--adding names from zzzz_tab_1 
update zzzz_tab_3 
set 
    x_names = t1.x_names 
    from (select nr, x_names from zzzz_tab_1) as t1 
    where zzzz_tab_3.nr = t1.nr; 
--adding age from zzzz_tab_2 
update zzzz_tab_3 
set 
    x_age = t1.x_age 
    from (select nr, x_age from zzzz_tab_2) as t1 
    where zzzz_tab_3.nr = t1.nr; 

select * from zzzz_tab_3; 

但是,這似乎並沒有在sqlite的工作。 我根據回覆here嘗試了以下代碼,但它也行不通。

with tx1 
as 
(select nr, x_names from zzzz_tab_1) 
replace into 
zzzz_tab_3 
select 
zzzz_tab_3.nr, zzzz_tab_3.x_names 
from zzzz_tab_3 
inner join tx1 on tx1.nr = zzzz_tab_3.nr 

這個操作是否可以在sqlite中使用?

- 澄清 -

基本上我有兩個表zzzz_tab_1和zzzz_tab_3

zzzz_tab_1

nr x_names 
1 AB 
2 BA 
3 CD 

zzzz_tab_3

nr x_names 
1 null 
2 null  
3 null 

我想從zzzz_tab_1數據添加到zzzz_tab_3 基於現場 結果的值(zzzz_tab_3)應

zzzz_tab_3

nr x_names 
1 AB 
2 BA 
3 CD 

PS:一可以創建一個新的表加入,但我的表是相當大的(30 Mio記錄)

+0

描述你想要解決什麼問題,以及結果應該是什麼。 –

回答

0

如果有人有興趣,一位同事提出了這種方法(並且它有效)。

update zzzz_tab_3 
set 
x_names = (select x_names from zzzz_tab_1 where zzzz_tab_3.nr = zzzz_tab_1.nr); 



update zzzz_tab_3 
set 
x_age = (select x_age from zzzz_tab_2 where zzzz_tab_3.nr = 
zzzz_tab_2.nr); 

-- verify 
select * from zzzz_tab_3;