PostgreSql查询数组值

时间:2017-02-19 08:33:23

标签: postgresql jsonb

我在postgresql中将以下JSON格式存储为JSONB列。

{DisplayName":"Bob marley","FName":"Bob","Title":null,"LName":"Marley","State":null,"EmailAddresses":["bob.marley@hotmail.com","bobmarley@gmail.com"]},
{DisplayName":"Bob martin","FName":"Bob ","Title":null,"LName":"Martin","State":null,"EmailAddresses":["bob.martin@hotmail.com","bobmartin@gmail.com"]}

我想查询以Bob开头的EmailAddresses数组。我能够使用LIKE和ILIKE运算符查询普通的字符串类型键,但是为了在ARRAY类型内搜索,会出现问题。 请指教。

1 个答案:

答案 0 :(得分:1)

如果要检查jsonb字段中数组的任何元素是否与掩码匹配:

SELECT *
  FROM jtable
 WHERE EXISTS (
        SELECT 1
          FROM jsonb_array_elements_text(jfield->'EmailAddresses') AS j
         WHERE j  ~ 'bob'
      )

                                                                                jfield                                                                                
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 {"FName": "Bob", "LName": "Marley", "State": null, "Title": null, "DisplayName": "Bob marley", "EmailAddresses": ["bob.marley@hotmail.com", "bobmarley@gmail.com"]}
 {"FName": "Bob ", "LName": "Martin", "State": null, "Title": null, "DisplayName": "Bob martin", "EmailAddresses": ["bob.martin@hotmail.com", "bobmartin@gmail.com"]}
(2 rows)

或者,如果您想要与掩码匹配的电子邮件列表:

WITH w AS (
    SELECT jsonb_array_elements_text(jfield->'EmailAddresses') AS emails,
           *
      FROM jtable
)
SELECT * FROM w WHERE emails ~ 'bobm'


       emails        |                                                                                jfield                                                                                
---------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 bobmarley@gmail.com | {"FName": "Bob", "LName": "Marley", "State": null, "Title": null, "DisplayName": "Bob marley", "EmailAddresses": ["bob.marley@hotmail.com", "bobmarley@gmail.com"]}
 bobmartin@gmail.com | {"FName": "Bob ", "LName": "Martin", "State": null, "Title": null, "DisplayName": "Bob martin", "EmailAddresses": ["bob.martin@hotmail.com", "bobmartin@gmail.com"]}
(2 rows)