如何将新项目附加到 PostgreSQL 中的数组类型列中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29319801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:50:20  来源:igfitidea点击:

How to append a new item into the array-type column in PostgreSQL

postgresqlpostgresql-9.2

提问by CodeRows

Im using PostgreSQL for my application,

我在我的应用程序中使用 PostgreSQL,

The task will be like this

任务将是这样的

There are users who use my app, and I need to maintain notification for each of them based on their activity so I get lots and lots of notifications for each user.

有些用户使用我的应用程序,我需要根据他们的活动为每个人维护通知,因此我会收到每个用户的大量通知。

so in general we just put all the notifications in a seperate table and we do map with user ID, so we can just fetch them, but now Im thinking to use either json/array datatype, so I can just put the entire notification set as array/json into the cell of each user row.

所以一般来说我们只是把所有的通知放在一个单独的表中,我们用用户 ID 映射,所以我们可以只获取它们,但现在我想使用 json/array 数据类型,所以我可以把整个通知设置为array/json 放入每个用户行的单元格中。

Which one is better, storing json or array?( Im using PHP at server side)

哪个更好,存储json或数组?(我在服务器端使用PHP)

and if we pick any one among the two, lets say we have some 10 notifications, and I got the 11th one, how do we append the new item into the array/json object in single execution(may be UPDATE statement)? I dont want to go in basic way like select the row, get the existing array/json add the new item in the end(process with PHP) and UPDATE it back- here it takes two executions where another change may occur and that brings dataloss

如果我们从两者中选择任何一个,假设我们有大约 10 个通知,而我得到了第 11 个,我们如何在单次执行中将新项目附加到数组/json 对象中(可能是 UPDATE 语句)?我不想采用基本方式,例如选择行,获取现有数组/json 最后添加新项目(使用 PHP 处理)并将其更新回来 - 这里需要执行两次,其中可能会发生另一个更改并导致数据丢失

so is there a way to do UPDATE query that just adds a new element or alters the existing element/node in array/json obejct types in PostgreSQL?

那么有没有一种方法可以进行 UPDATE 查询,它只添加一个新元素或更改 PostgreSQL 中 array/json 对象类型中的现有元素/节点?

回答by samed.yildirim

To append an item to array in PostgreSQL you can use || operator or array_append function.

要将项目附加到 PostgreSQL 中的数组,您可以使用 || 运算符或 array_append 函数。

With || operator

与 || 操作员

UPDATE table SET array_field = array_field || 'new item' WHERE ...

With array_append function

使用 array_append 函数

UPDATE table SET array_field = array_append(array_field,'new item') WHERE ...

Also you can visit this page for array, http://www.postgresql.org/docs/current/interactive/functions-array.html

你也可以访问这个数组页面,http://www.postgresql.org/docs/current/interactive/functions-array.html

I don't know how to do it with json data type.

我不知道如何使用 json 数据类型。