json - 如何在 PostgreSQL 9.3 中查询 JSON 数组?

标签 json postgresql

我创建了一个名为“delivery”的表,其中一个字段是一个 JSON 数组。

CREATE TABLE delivery
(
  id text NOT NULL,
  date timestamp with time zone NOT NULL,
  items json NOT NULL,
  CONSTRAINT delivery_pkey PRIMARY KEY (id)
)

这里是示例数据:

"1", "2012-01-08 20:54:38.541989+00", "[ {"id":1, "qty": 10 }, {"id":2, "qty": 300}]"
"2", "2012-01-08 22:44:10.016285+00", "[ {"id":1, "qty": 200}]"

如何获取“items”字段中“id”等于 1 的行?

最佳答案

你可以像这样使用子查询和 json 函数来做到这一点:

SELECT * FROM delivery
WHERE '1' in (
   select a->>'id' from json_array_elements(items) a
)

这是 SQL fiddle一起玩。

关于json - 如何在 PostgreSQL 9.3 中查询 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24733196/

相关文章:

java - 自动发现没有 get 前缀的 getter

json - 如何将 Pandas 系列转换为所需的 JSON 格式?

postgresql - 使用命令行检查一个请求是否失败

sql - Postgresql - "ERROR: syntax error at or near "-“尝试将数字参数传递给存储过程时

android - Android 4.0 上的 PostgreSQL JDBC 连接失败

postgresql - 冲突时(UUid,date_trunc ('day',时间戳))

java - JSON 数组到 ArrayList<List<String>>

json - 删除 key :value from an JSON object using jq

mysql - postgres 和 mysql 上的通用大写搜索不起作用

c# - HttpRequestException——这是客户端或服务器问题吗?