Postgres成功地从另一个表中追加(更新和插入),但一个值的id值重复



我正在尝试将数据从一个表上传到另一个表。它们有一些重复的值。第一张表是这样的,表a:

id | deviceserial | time_difference
----+--------------+-----------------
1 | 636363636891 |               3
2 | 636363636890 |             123
3 | 6625839827   |              29
4 | 6625839832   |              60
5 | 6625839830   |             120
6 | 6625839828   |               4
7 | 6625839833   |              60
Another table name table-b:
id | deviceserial | time_difference
----+--------------+-----------------
1 | 636363636891 |               3
2 | 636363636890 |             123
3 | 6625839835   |              60
4 | 6625839827   |              29
5 | 6625839832   |              60
6 | 6625839830   |             120
7 | 6625839828   |               4
8 | 6625839833   |              60

我正在尝试从表-b到表-a的UPSERT,查询如下:

INSERT INTO table-a (id,deviceSerial,time_difference) SELECT id,deviceSerial,time_difference FROM table-b ON CONFLICT (deviceserial) DO  UPDATE SET time_difference=device_usage1.time_difference + excluded.time_difference;

我得到了这个结果。

id | deviceserial | time_difference
----+--------------+-----------------
1 | 636363636891 |               6
2 | 636363636890 |             246
3 | 6625839835   |              60
3 | 6625839827   |              58
4 | 6625839832   |             120
5 | 6625839830   |             240
6 | 6625839828   |               8
7 | 6625839833   |             120

它的更新和插入成功。但是一个id重复(非重复的deviceSerial(。原因是什么?

尝试从SELECT中排除id。假设idtable-a中的一个自动递增值,则在插入新值时将生成一个新的唯一ID。

INSERT INTO table-a (id,deviceSerial,time_difference)
SELECT deviceSerial,time_difference FROM table-b 
ON CONFLICT (deviceserial) DO 
UPDATE SET time_difference=device_usage1.time_difference + excluded.time_difference;

如果您想强制执行唯一性,我强烈建议您在id中添加一个约束。它看起来像是表的主键。您也可以完全删除id,只使用deviceSerial作为主键,因为看起来这个值也必须是唯一的。

最新更新