![](/img/trans.png)
[英]Postgres query to return rows where json in the json column contains array elements more than one
[英]Postgres Query JSON Array that contains something
Postgres有這個JSON數據類型,我想知道如何在JSON數組中查詢數據? 我正在使用Postgres 9.3.1
我已插入到PUBLISHER表中,其中包含以下兩個字段的名稱:string和data:json
INSERT INTO PUBLISHER (name, data) VALUES ('PUB1', [{"code":"PA1","author":"James","type":"Novel"},{"code":"PA2","author":"John","type":"Science"}]
INSERT INTO PUBLISHER (name, data) VALUES ('PUB2', [{"code":"PA1","author":"Dickens","type":"Novel"},{"code":"PA2","author":"Tom","type":"Comic"}]
我想查詢並列出“Novel”類型的作者。 在這種情況下,應該是輸出的“詹姆斯”和“湯姆”。
這種查詢的東西:
select name, authorfromdata from publisher where data->type is "Novel"
您可以使用json_array_elements
函數從數組生成SETOF json
:
SELECT name, json_array_elements(data) AS author
FROM publisher
有了它,你可以將它用作子查詢,這樣你就可以過濾你想要的東西,例如:
SELECT DISTINCT author->>'author'
FROM (
SELECT name, json_array_elements(data) AS author
FROM publisher
) t
WHERE t.author->>'type' = 'Novel';
請注意,如果此表中有許多行,則此類查詢的性能(至少對於當前版本9.3)將非常糟糕。 我建議你將數據規范化為表格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.