sql - jsonb 在数组中查找一个值

标签 sql arrays json postgresql jsonb

有这样一个数据结构:

Column "recipient" type jsonb

{
  "phoneNumbers": [
    {
      "isDefault": true,
      "type": "MOBILE",
      "number": "3454654645"
    },
    {
      "isDefault": true,
      "type": "MOBILE",
      "number": "12423543645"
    }
  ]
}

我需要按号码编写搜索请求。在postgres文档中,我没有找到在数组中按值搜索,只是通过索引获得。不适合我

我做了一个这样的查询,它被执行了,但是还有其他方法来搜索数组吗?

SELECT * 
FROM my_table
WHERE recipient -> 'phoneNumbers' @> '[{"number":3454654645}]'

最佳答案

是的,这几乎是最好的方法。

如果您在接收者上有 (GIST) 索引,则您的病情将不会使用该索引。但以下内容可以使用这样的索引:

SELECT * 
FROM my_table
WHERE recipient @> '["phoneNumbers": {"number":3454654645}]}'

如果您使用的是 Postgres 12 或更高版本,您还可以使用 JSON 路径表达式:

SELECT * 
FROM my_table
WHERE recipient @@ '$.phoneNumbers[*].number == "12423543645"'

如果您无法将 JSON 对象传递给查询,则可以使用 EXISTS 子选择:

SELECT mt.*
FROM my_table mt
WHERE EXISTS (SELECT * 
              FROM jsonb_array_elements_text(mt.recipient -> 'phoneNumbers') as x(element)
              WHERE x.element ->> 'number' = '3454654645')

'3454654645' 可以作为参数传递给您的查询。但这永远不会使用索引。

关于sql - jsonb 在数组中查找一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67017846/

相关文章:

sql - Sql Server 中的 SUM 显示错误

sql - 如何构建数据……顺序的还是分层的?

arrays - 蒙戈更新 : upsert an element in array

javascript - 在 C# 和 JavaScript 之间传递日期

sql - 做哪一项更有效

mysql - 触发在特定日期删除数据库

c# - 使用 Newtonsoft 将 JSON 数组反序列化为元组列表

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

json - Jackson 反序列化递归对象

json - 我无法使用从请求中获取的数据创建结构