简体   繁体   English

Postgres查询包含内容的JSON数组

[英]Postgres Query JSON Array that contains something

Postgres has this JSON datatype and I am wondering how can I query data inside a JSON array ? Postgres有这个JSON数据类型,我想知道如何在JSON数组中查询数据? I am using Postgres 9.3.1 我正在使用Postgres 9.3.1

I have inserted into PUBLISHER table that has these 2 fields name: string and data: json 我已插入到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"}] 

I want to do a query and list out authors with the type "Novel". 我想查询并列出“Novel”类型的作者。 In this case it would be "James" and "Tom" that should be the output. 在这种情况下,应该是输出的“詹姆斯”和“汤姆”。

Something of this sort of query: 这种查询的东西:

select name, authorfromdata from publisher where data->type is "Novel"

You can use the json_array_elements function to generate a SETOF json from an array: 您可以使用json_array_elements函数从数组生成SETOF json

SELECT name, json_array_elements(data) AS author
FROM publisher

Having that, you can use it as a subquery, so you can filter what you want, eg: 有了它,你可以将它用作子查询,这样你就可以过滤你想要的东西,例如:

SELECT DISTINCT author->>'author'
FROM (
    SELECT name, json_array_elements(data) AS author
    FROM publisher
) t
WHERE t.author->>'type' = 'Novel';

Just note that if you have many rows in this table, the performance of such queries (at least for current version, 9.3) will be really bad. 请注意,如果此表中有许多行,则此类查询的性能(至少对于当前版本9.3)将非常糟糕。 I'd recommend you to normalize the data into tables. 我建议你将数据规范化为表格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM