【问题标题】:postgres insert data from an other table inside array type columnspostgres 在数组类型列中插入来自另一个表的数据
【发布时间】: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


【解决方案1】:

基本上,您的查询失败是因为表的结构不匹配 - 所以您不能insert into test select * from test2

您可以通过在select 列表中添加“假”列来解决此问题,如下所示:

insert into test
select idweb, 'foo', 0, quantities, dates  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); 

但这看起来比需要的要复杂得多。本质上,你想要一个update 声明,所以我只推荐:

update test
set
    dates = test2.dates || test.dates,
    quantities = test2.quantities || test.quantities
from test2
where test.id = test2.idweb

请注意,这里使用的是|| 连接运算符,而不是array_cat() - 写起来更短。

Demo on DB Fiddle

编号 |类别 |数量 |数量 |日期 -: | :------- | --------: | :--------- | :------------ 2 |猫2 | 99 | {22} | {879889} 1 |猫1 | 33 | {34,66} | {8776,123678}

【讨论】:

  • 感谢专线小巴!您的解决方案完全符合我的预期!
猜你喜欢
  • 2015-03-24
  • 1970-01-01
  • 2014-09-09
  • 2021-11-11
  • 2012-12-01
  • 2020-01-30
  • 2017-08-20
  • 2018-07-25
  • 2021-02-26
相关资源
最近更新 更多