Postgres有这个JSON数据类型,我想知道如何在JSON数组中查询数据?我正在使用Postgres 9.3.1
我已插入PUBLISHER表,其中包含以下两个字段名称:字符串和数据: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”类型的作者。在这种情况下,应该是输出的“James”和“Tom”。
这种查询:
select name, authorfromdata from publisher where data->type is "Novel"
答案 0 :(得分:6)
您可以使用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)将非常糟糕。我建议你将数据规范化为表格。