PostgreSQL update from 根据 A 表更新 B 表
PostgreSQL About 775 words准备工作
-- 创建表1
create table t1(id integer, name text);
-- 创建表2
create table t2(id integer, name text);
-- 表1中填充数据
insert into t1(id, name) values(1, 't111111');
insert into t1(id, name) values(2, 't222222');
insert into t1(id, name) values(3, 't333333');
-- 表2中填充数据
insert into t2(id) values(2);
insert into t2(id) values(5);
insert into t2(id,name) values(6,'t66666');
查看当前表1数据
z-blog=# select * from t1;
id | name
----+---------
1 | t111111
2 | t222222
3 | t333333
(3 rows)
查看当前表2数据
z-blog=# select * from t2;
id | name
----+--------
2 |
5 |
6 | t66666
(3 rows)
执行更新
update from
语句可以根据表1更新表2。
update t2 set name = t1.name from t1 where t2.id = t1.id;
查看更新后表2数据
z-blog=# select * from t2;
id | name
----+---------
2 | t222222
5 |
6 | t66666
(3 rows)
Views: 4,760 · Posted: 2021-01-04
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...