在数组类型的列中插入其他表的数据。

问题描述 投票:0回答:1

我在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]);

我试图从表test2更新数据到表test,只更新表test的ARRAY内相同id的行,并保持原值。

我使用INSERT来解决冲突。

  • category
  • 运行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.comfrs8BpjDUCciyZVwu5efNJE0

是否有更好的方法从表test2更新表test,或者我在哪里丢失了sql?

更新显示结果需要在表测试。

**Schema (PostgreSQL v11)**


| id  | quantitie | quantities | dates       |  category |
| --- | --------- | ---------- | ----------- | --------- |
| 2   | 99        | 22         | 879889      | cat2      |
| 1   | 33        | 34,66      | 8776,123678 | cat1      |


arrays postgresql insert sql-insert
1个回答
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); 

但这看起来比需要的要复杂得多 But this looks much more convoluted than needed. 本质上,你想要一个 update 语句,所以我只推荐。

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

请注意,这个UES || 连词运算符,而不是 array_cat() - 写起来比较短。

DB Fiddle的演示:

身份证 
© www.soinside.com 2019 - 2024. All rights reserved.