2017-02-19 91 views
0

我有以下JSON格式存儲爲postgresql中的JSONB列。PostgreSql查詢數組值

{DisplayName":"Bob marley","FName":"Bob","Title":null,"LName":"Marley","State":null,"EmailAddresses":["[email protected]","[email protected]"]}, 
{DisplayName":"Bob martin","FName":"Bob ","Title":null,"LName":"Martin","State":null,"EmailAddresses":["[email protected]","[email protected]"]} 

我想查詢它以Bob開頭的EmailAddresses陣列。我能夠使用LIKE和ILIKE運算符查詢正常的字符串類型鍵,但是在ARRAY類型內部搜索會產生問題。 請指教。

回答

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": ["[email protected]", "[email protected]"]} 
{"FName": "Bob ", "LName": "Martin", "State": null, "Title": null, "DisplayName": "Bob martin", "EmailAddresses": ["[email protected]", "[email protected]"]} 
(2 rows) 

或者,如果你想要的電子郵件列表匹配掩碼:

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


     emails  |                    jfield                     
---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
[email protected] | {"FName": "Bob", "LName": "Marley", "State": null, "Title": null, "DisplayName": "Bob marley", "EmailAddresses": ["[email protected]", "[email protected]"]} 
[email protected] | {"FName": "Bob ", "LName": "Martin", "State": null, "Title": null, "DisplayName": "Bob martin", "EmailAddresses": ["[email protected]", "[email protected]"]} 
(2 rows) 
+0

大,三江源 – puneet