2016-11-09 40 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;