2017-03-03 60 views
1
CREATE TABLE tableTestJSON (
    id serial primary key, 
    data jsonb 
); 

INSERT INTO tableTestJSON (data) VALUES 
('{}'), 
('{"a": 1}'), 
('{"a": 2, "b": ["c", "d"]}'), 
('{"a": 1, "b": {"c": "d", "e": true}}'), 
('{"b": 2}'); 

我可以選擇值。這沒有問題。查詢JSON PostgreSQL

SELECT * FROM tableTestJSON; 

我可以測試兩個JSON對象是否與此查詢相同。

SELECT * FROM tableTestJSON WHERE data = '{"a":1}'; 

此查詢的輸出是:

ID |數據 ---- + ------ 1 | {「一」:1} (1行)

但我有一個問題: 可以說我有一欄:

{a: 30} 
{a: 40} 
{a: 50} 

在這種情況下,我怎麼能查詢所有包含的元素a = 30或a = 40。我無法找到'or'的任何解決方案,例如

select * from table where a in (10,20); // ?? 

或 我該如何查詢這種情況?

回答

1

提取使用the operator ->> JSON對象的值:

select * 
from tabletestjson 
where (data->>'a')::int in (1, 2) 

id |     data     
----+-------------------------------------- 
    2 | {"a": 1} 
    3 | {"a": 2, "b": ["c", "d"]} 
    4 | {"a": 1, "b": {"c": "d", "e": true}} 
(3 rows) 
+0

另外我測試另一asnwer這樣。 Like this query:SELECT * FROM tableTestJSON WHERE data#>'{a}'IN('10','20'); 謝謝。 – aemre