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

时间:2024-04-18 16:25:00

示例

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
 a | b | c
---+---+---
 1 | 2 | 3
 (1 rows)

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

1
2
3
4
5
6
7
INSERT INTO reason_t2 VALUES (1, 4, 5),(2, 6, 7) ON CONFLICT(a) DO NOTHING;
SELECT * FROM reason_t2 ORDER BY 1;
 a | b | c
---+---+----
 1 | 2 | 3
 2 | 6 | 7
(2 rows)

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

1
2
3
4
5
6
7
8
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;
 a | b | c
---+---+----
 1 | 4 | 5
 2 | 6 | 7
 3 | 8 | 9
 (3 rows)

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

1
2
3
4
5
6
7
8
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;
 a | b | c
---+---+---
 1 | 4 | 5
 2 | 7 | 8
 3 | 8 | 9
(3 rows)

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

1
2
3
4
5
6
7
8
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;
 a | b | c
---+---+---
 1 | 3 | 2
 2 | 7 | 8
 3 | 8 | 9
(3 rows)
support.huaweicloud.com/sqlreference-830-dws/dws_06_0237.html