sql - 在数组列上插入
问题描述
我正在尝试对数组列进行 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 不起作用,因为它一次只附加一个项目,而我需要附加一个数组
解决方案
您可以使用||
将一个数组附加到另一个数组:
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;
推荐阅读
- android - 在 viewModelScope 中设置后 LiveData 值为 null
- java - Minecraft-moding:Mod 仅在 IDE 中有效,但在导出为 jar 时无效
- intellij-idea - Intellij 插件开发:toolWindow 扩展在不同项目窗口中打开时为空白
- html - 增加html中文本框的大小
- sql - 此 SELECT 的最佳索引是什么?
- java - 为什么我的 java 代码在使用 SmbFileInputStream 和 BufferedOutputStream 时进入无限循环
- javascript - 如何干净地设置 Angular 2+ 组件,以便它们可以用作弹性项目?
- iis-8 - 垃圾不断插入 IIS 反向代理 URL
- c++ - 通过 TCP 套接字发送数据不起作用。错误:没有错误
- java - 如何修复此编程代码?(MOOCFI java week7 练习8)