携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天
批量操作可以减少数据库与应用程序的交互次数,提高数据处理的吞吐量。那么在pg中如何实现批量插入、更新、删除操作呢?
1、批量插入
bill@bill=>create table tbl1(id int,info text,ctr_time timestamp);
CREATE TABLE
–方法一
使用最基本的values(),(),()…的方法
bill@bill=>insert into tbl1 (id,info,crt_time) values (1,'test',now()), (2,'test2',now()), (3,'test3',now());
INSERT 0 3
–方法二
使用insert into … select的方法
bill@bill=>insert into tbl1 (id, info ,crt_time) select generate_series(1,10000),'test',now();
INSERT 0 10000
–方法三
BEGIN;
…insert…;
END;
bill@bill=> begin;
BEGIN
bill@bill=>insert into tbl1 (id,info,crt_time) values (1,'test',now());
INSERT 0 1
bill@bill=>insert into tbl1 (id,info,crt_time) values (2,'test2',now());
INSERT 0 1
bill@bill=>insert into tbl1 (id,info,crt_time) values (3,'test3',now());
INSERT 0 1
bill@bill=>end;
COMMIT
–方法四
copy协议
bill@bill=> copy tbl from '/home/pg12/a.sql';
COPY 100
2、批量更新
from后面用其他表名代替可以实现多表JOIN批量更新。
bill@bill=>update test set info=tmp.info from (values (1,'new1'),(2,'new2'),(6,'new6')) as tmp (id,info) where test.id=tmp.id;
UPDATE 3
3、批量删除
using后面用其他表名代替可以实现多表JOIN批量删除。一般删除大量数据例如删除全表数据建议用truncate代替。
bill@bill=>delete from test using (values (3),(4),(5)) as tmp(id) where test.id=tmp.id;
DELETE 3
需要注意的是:
对于update , delete 批量操作,如果JOIN不是一一对应时,更新目标可能会随机匹配。
例子:
bill@bill=>create table t1 (id int primary key, info text);
CREATE TABLE
bill@bill=>create table t2(id int, info text);
CREATE TABLE
bill@bill=>insert into t1 select generate_series(1,10), 't1';
INSERT 0 10
bill@bill=>insert into t2 values (1,'t2');
INSERT 0 1
bill@bill=>insert into t2 values (1,'t2');
INSERT 0 1
bill@bill=>insert into t2 values (1,'t3');
INSERT 0 1
bill@bill=>insert into t2 values (1,'t4');
INSERT 0 1
bill@bill=>update t1 set info=t2.info from t2 where t1.id=t2.id;
UPDATE 1
bill@bill=>select * from t1 where id=1;
id | info
----+------
1 | t2
(1 row)