【问题标题】:Check Array Object as Part of WHERE Clause检查数组对象作为 WHERE 子句的一部分
【发布时间】:2016-05-03 13:02:29
【问题描述】:

我正在使用 postgres 9.4 和 jsonb 类型。我有下表:

CREATE TABLE jsonb_test (iid serial NOT NULL, data jsonb)

以及该表中的以下json数据:

{"date": "2016-01-01T00:00:00.000Z", "items": [{"name": "bottles", "price": 12}, {"name": "caps", "price": 20}], "customer": {"name": "Customer 1", "email": "customer1@gmail.com"}}
{"date": "2015-12-01T00:00:00.000Z", "items": [{"name": "bottles", "price": 1}, {"name": "caps", "price": 50}], "customer": {"name": "Customer 2", "email": "customer2@gmail.com"}}

我想做的是获取所有商品价格大于 30 的行。在这种情况下,这将返回 Customer 2 行。

这是我目前的查询:

SELECT * FROM jsonb_test WHERE jsonb_array_elements(jsonb_extract_path(data, 'items')) #> '{price}' > '0'

但这会失败并出现错误ERROR: argument of WHERE must not return a set

谁能告诉我怎么做?是否可以对任意级别的嵌套执行此操作?

谢谢!

【问题讨论】:

标签: postgresql-9.4 jsonb


【解决方案1】:

试试这样的:

SELECT * FROM jsonb_test, jsonb_array_elements(jsonb_test.data->'items') AS a WHERE (a->>'price') > '0'

【讨论】:

  • 这很有效,并且作为提供项目元素本身的额外好处。不过我想知道,这可以嵌套吗?如果我有一个对象数组也有一个对象数组,如何查询这些对象?
  • @shortspider 试试这个例子stackoverflow.com/questions/32571338/…
【解决方案2】:

提这个:

SELECT * FROM json_test WHERE jsonb_test.data #> '{items,price}' > '30';

我想要做的是:给我对象,其中元素项目有一个子对象,其元素价格等于整数“1”。

在这里查看一些示例:http://schinckel.net/2014/05/25/querying-json-in-postgres/

【讨论】:

  • 这不会为我返回任何结果,即使我将比较更改为 > '0'
  • 我在 FROM 之后有一个拼写错误 jsonb_test。试试看
  • 我做了,但仍然一无所获。这是查询:SELECT * FROM jsonb_test WHERE jsonb_test.data #> '{items,price}' > '0';
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2021-08-23
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多