数据仓库服务 GAUSSDB(DWS)-UPSERT:示例

时间:2024-10-21 15:01:28

示例

创建表reason_t2,并向表中插入数据:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
DROP TABLE IF EXISTS reason_t2;
CREATE TABLE reason_t2
(
  a    int primary key,
  b    int,
  c    int
);

INSERT INTO reason_t2 VALUES (1, 2, 3);
SELECT * FROM reason_t2 ORDER BY 1;

向表reason_t2中插入两条数据,一条有冲突,一条无冲突。有冲突的数据进行忽略,无冲突的数据进行插入:

1
2
INSERT INTO reason_t2 VALUES (1, 4, 5),(2, 6, 7) ON CONFLICT(a) DO NOTHING;
SELECT * FROM reason_t2 ORDER BY 1;

向表reason_t2中插入数据,一条有冲突,一条无冲突。有冲突的数据进行更新,无冲突的数据进行插入:

1
2
INSERT INTO reason_t2 VALUES (1, 4, 5),(3, 8, 9) ON CONFLICT(a) DO UPDATE SET b = EXCLUDED.b, c = EXCLUDED.c;
SELECT * FROM reason_t2 ORDER BY 1;

根据过滤条件筛选被更新的行:

1
2
INSERT INTO reason_t2 VALUES (2, 7, 8) ON CONFLICT (a) DO UPDATE SET b = excluded.b, c = excluded.c  WHERE reason_t2.c = 7;
SELECT * FROM reason_t2 ORDER BY 1;

向表reason_t中插入数据,有冲突的数据进行更新并调整更新映射关系,即c列更新到b,b列更新到c:

1
2
INSERT INTO reason_t2 VALUES (1, 2, 3) ON CONFLICT (a) DO UPDATE SET b = excluded.c, c = excluded.b;
SELECT * FROM reason_t2 ORDER BY 1;
support.huaweicloud.com/sqlreference-dws/dws_06_0237.html