postgresql - 通过数组索引和对象属性查询 json 字段

标签 postgresql

我有一个专栏:

[
   {
      "type":"menu",
      "prompt": {
            "type":"say",
            "message":"This is a menu. Pick option 1 or 2."
      }
   }
]

第一层对象可以包含多种类型和任意数量的类型。我的目标(用于自动化测试,而不是生产,因此效率低下)是找到包含任何 column.*.type = menu 的记录。

基于 https://stackoverflow.com/a/22687653/197606我知道我可以提供一个数字索引,但是运行查询 SELECT * FROM my_table WHERE 'my_column'->0->'type' = 'menu' 会抛出错误:

ERROR:  operator is not unique: unknown -> integer
LINE 1: SELECT * FROM my_table WHERE 'my_column'->0->'type' =...
                                                       ^
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.
Query failed
PostgreSQL said: operator is not unique: unknown -> integer
Hint: Could not choose a best candidate operator. You might need to add explicit type casts.

虽然指定 0 的数字索引适用于此特定用例并且是一个可接受的答案,但我更喜欢一种对列索引不挑剔的方法。

最佳答案

你可以使用这个:

SELECT * FROM my_table WHERE my_column->0->>'type' = 'menu'

关于postgresql - 通过数组索引和对象属性查询 json 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43790747/

相关文章:

sql - 在 SQL 中插入缺失值

大型查询 : An I/O error occurred while sending to the backend 上的 Java PostgreSQL 错误

sql - PostgreSQL json路径表达式以查找具有特定键的第一个数组元素

没有选择/插入/删除/更新的sql函数

postgresql - 如何使用指定的外键创建记录?

postgresql - TypeORM:在 PostgreSQL 中自动生成 UUID

SQL:在唯一索引中进行类型转换

python - 在 psycopg2 中将表名作为参数传递

postgresql - 如何使用unix套接字配置postgresql/pgbouncer?

sql - postgreSQL 选择昨天的值,月平均值