首页 > 解决方案 > 在数组列上插入

问题描述

我正在尝试对数组列进行 upsert,但我无法获得以下结果。

表名设置

id primary key unique
user_id foreign_key integer unique
friends array
tags array
count integer
created_at datetime
updated_at datetime
select * from settings order by id asc limit 1;
id                         | 177 
user_id                    | 111
friends                    | {1,2,3}
tags                       | {4,5}
created_at                 | 2020-01-23 10:30:27.814489
updated_at                 | 2020-02-29 00:00:00
count                      | 5             
 insert into settings(
   user_id, friends, tags, created_at, updated_at)
 VALUES (111, '{6,7}', '{5000,5001}', now()::date , now()::date )
 on conflict (user_id) do 
 update set
   friends = array_cat(excluded.friends, '{6,7}'),
   tags = array_cat(excluded.tags, '{5000,5001}'),
   updated_at = now()::date;

在我检查结果时运行上述查询后

select * from settings order by id asc limit 1;
id                         | 177 
user_id                    | 111
friends                    | {6,7,6,7}
tags                       | {5000,5001,5000,5001}
created_at                 | 2020-01-23 10:30:27.814489
updated_at                 | 2020-02-29 00:00:00
count                      | 5             

我正在失去我的旧价值观。此外,新值被插入两次。谁能帮我这个

注意:array_append 不起作用,因为它一次只附加一个项目,而我需要附加一个数组

标签: sqlpostgresql

解决方案


您可以使用||将一个数组附加到另​​一个数组:

insert into settings
  (user_id, friends, tags, created_at, updated_at)
VALUES 
  (111, '{6,7}', '{5000,5001}', current_timestamp, current_timestamp)
on conflict (user_id) do 
 update set
   friends = settings.friends || excluded.friends,
   tags = settings.tags || excluded.tags,
   updated_at = current_timestamp;

推荐阅读