【发布时间】:2020-09-09 19:01:35
【问题描述】:
我在 Postgres 11 上有这样的拖表,其中包含一些 ARRAY 类型的列。
CREATE TABLE test (
id INT UNIQUE,
category TEXT NOT NULL,
quantitie NUMERIC,
quantities INT[],
dates INT[]
);
INSERT INTO test (id, category, quantitie, quantities, dates) VALUES (1, 'cat1', 33, ARRAY[66], ARRAY[123678]);
INSERT INTO test (id, category, quantitie, quantities, dates) VALUES (2, 'cat2', 99, ARRAY[22], ARRAY[879889]);
CREATE TABLE test2 (
idweb INT UNIQUE,
quantities INT[],
dates INT[]
);
INSERT INTO test2 (idweb, quantities, dates) VALUES (1, ARRAY[34], ARRAY[8776]);
INSERT INTO test2 (idweb, quantities, dates) VALUES (3, ARRAY[67], ARRAY[5443]);
我正在尝试仅在具有相同 ID 的行上将数据从表 test2 更新到表 test。在表格测试的 ARRAY 中并保持原始值。
我在冲突时使用 INSERT,
- 如何仅更新 2 列数量和日期。
- 在我运行 sql 的时候也遇到了一个我不明白来源的错误。
Schema Error: error: column "quantitie" is of type numeric but expression is of type integer[]
INSERT INTO test (SELECT * FROM test2 WHERE idweb IN (SELECT id FROM test))
ON CONFLICT (id)
DO UPDATE
SET
quantities = array_cat(EXCLUDED.quantities, test.quantities),
dates = array_cat(EXCLUDED.dates, test.dates);
https://www.db-fiddle.com/f/rs8BpjDUCciyZVwu5efNJE/0
有没有更好的方法从表 test2 更新表 test,或者我缺少 sql?
更新以显示表测试所需的结果:
**Schema (PostgreSQL v11)**
| id | quantitie | quantities | dates | category |
| --- | --------- | ---------- | ----------- | --------- |
| 2 | 99 | 22 | 879889 | cat2 |
| 1 | 33 | 34,66 | 8776,123678 | cat1 |
【问题讨论】:
-
你能显示你想要得到的结果吗?
-
我更新了我的问题以显示我在寻找什么,谢谢@Jeremy
标签: sql arrays postgresql sql-update sql-insert