Postgres 9.5查询匹配数组

时间:2016-07-21 17:17:00

标签: sql arrays json postgresql postgresql-9.5

我在表 Houses 中有一个列地址,类型为jsonb[],其中包含一个如下所示的数组:

"{
  "{\"zip\": \"13203-1807\", 
  \"city\": \"\SYRACUSE\", 
  \"state\": \"NEW YORK\", 
  \"street\": \"\999 PROSPECT AVENUE\"}"
 }"

我正在尝试查询地址城所在的所有房屋" Syracuse&#34 ;;到目前为止我有:

SELECT * FROM Houses WHERE address -> 'city' = 'SYRACUSE'

并收到此错误:

No operator matches the given name and argument type(s). You might need to add explicit type casts.

我查看了PG Official Documentation on JSON Functions and Operators以及几个StackOverflow答案都无济于事。

1 个答案:

答案 0 :(得分:1)

好的,正如上面的评论中所提到的,您正在尝试在postgresql数组上使用JSON运算符,这就是您遇到类型错误的原因。有几种方法可以解决这个问题,具体取决于您实际想要在该字段中存储的内容。

对于这些例子,我将假设下表:

CREATE TABLE houses (id INT, address <some datatype>);

如果你想让它成为jsonb的postgres数组,你必须解压缩数组,你可以这样做:

WITH all_addresses AS (
  SELECT id, unnest(address) as add
    FROM houses)
SELECT *
  FROM houses h
  WHERE
    id IN (SELECT id
             FROM all_addresses
             WHERE add->'city' = to_jsonb('SYRACUSE'::text));

另一方面,如果你想使用JSON数组,那么查询可能看起来像这样(非常相似,因为你仍然需要取消数组):

WITH all_addresses AS (
  SELECT id, jsonb_array_elements(address) as add
    FROM houses)
SELECT *
  FROM houses h
  WHERE
    id IN (SELECT id
             FROM all_addresses
             WHERE add->'city' = to_jsonb('SYRACUSE'::text));

我无法从您的问题中说出来,但您可能只在该列中每行存储一个地址(基于您的示例数据和该列的事实)被命名为地址&#39;而不是&#39;地址&#39;)。如果是这种情况,您的查询会变得更简单:

SELECT *
  FROM houses
  WHERE address->'city' = to_jsonb('SYRACUSE'::text);