2016-09-14 79 views
3

如果我有一個jsonb柱領域,如所謂的value查詢JSONB與數組字段

{"id": "5e367554-bf4e-4057-8089-a3a43c9470c0", 
"tags": ["principal", "reversal", "interest"],,, etc} 

我如何才能找到包含給定的標籤,例如所有記錄: 如果給:["reversal", "interest"] 它應該找到所有具有「逆轉」或「利息」或兩者的記錄。

我的實驗讓我這個令人厭惡的東西遠:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->>'tags' LIKE '%"principal"%'; 

當然,這是完全錯誤的,低效的

回答

1

事實證明,你可以使用這裏描述的酷jsonb運營商:

https://www.postgresql.org/docs/9.5/static/functions-json.html

所以原始查詢沒有太大變化:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->'tags' ?| array['reversal', 'interest']; 

在我的情況我還需要躲避???|),因爲我使用所謂的「準備好的聲明中」在那裏你通過查詢字符串和參數,JDBC和問號就像佔位PARAMS:

https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

1

假設你正在使用PG 9.4+,您可以使用jsonb_array_elements()功能:

SELECT DISTINCT abu.* 
FROM account_balance_updated abu, 
    jsonb_array_elements(abu.value->'tags') t 
WHERE t.value <@ '["reversal", "interest"]'::jsonb; 
+0

這個工作,非常感謝! – Agzam

+0

呃......現在我想知道是否可以通過修改'where'部分來實現這個目標?否則,我將不得不重構代碼的其他部分(構成整個查詢)。因此,如果我的查詢開始時間是'select account from account_balance_updated where value @>'{}':: jsonb and value - >>'id'='48c017c2-40c0-4462-ba2b-c2f176a2d086'並且... '我可以通過追加一些魔法來像這樣查詢來達到同樣的訣竅(就像在你的答案中一樣)? – Agzam

+0

我做了這個'和價值 - >'標籤'? array ['interest','reversal']'並且它似乎在工作 – Agzam