mydb=> create table test_1 (id integer, name varchar(32)); CREATE TABLE mydb=> insertinto test_1 values (1,'a'),(2,'b'),(3,'c'); INSERT03 mydb=> create table test_1_bak asselect * from test_1 where1=2; SELECT0 mydb=> select * From test_1; id | name ----+------ 1 | a 2 | b 3 | c (3 rows) mydb=> select * from test_1_bak; id | name ----+------ (0 rows)
场景一:CTE 基本用法
删除表 test_1 数据,并将删除的数据备份在表 test_1_bak
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
mydb=> WITH deleted as (deletefrom test_1 where id=1returning id,name) mydb-> insertinto test_1_bak select * From deleted; INSERT01
mydb=> select * from test_1; id | name ----+------ 2 | b 3 | c (2 rows)
mydb=> select * from test_1_bak; id | name ----+------ 1 | a (1 row)
mydb=> WITH test_1_deleted as (deletefrom test_1 where id=2returning *) mydb-> select * from test_1_deleted; id | name ----+------ 2 | b (1 row) mydb=> select * from test_1; id | name ----+------ 3 | c (1 row)
mydb=> select * From test_2 limit3; id | name ----+------ 1 | AAA 2 | AAA 3 | AAA
mydb=> WITH test_1_deleted as (deletefrom test_1 where id<7returning *) , mydb-> delete_count as (selectcount(*) as total from test_1_deleted) mydb-> update test_2 mydb-> set name='this is a test' mydb-> from delete_count d mydb-> where id=d.total; UPDATE1
mydb=> select * From test_2 where name='this is a test'; id | name ----+---------------- 4 | this is a test