[英]Postgresql query array of objects in JSONB field filter Specific Object
CREATE TABLE company (id SERIAL, companyJson JSONB);
CREATE INDEX comapny_gin_idx ON company USING gin (companyJson);
INSERT INTO company (id, companyJson)
VALUES (1, '[{"name": "t", "company": "company1"}]');
INSERT INTO company (id, companyJson)
VALUES (2, '[{"name": "b", "company":"company2"}, {"name": "b", "company":"company3"}]');
SELECT * FROM company WHERE companyJson @> '[{"company": "company2" , "name": "b"}]';
The output of the above program is上面程序的输出是
2 [{"name": "b", "company": "company2"}, {"name": "b", "company": "company3"}]
Is there anyway to return {"name": "b", "company": "company2"} instead whole row.无论如何要返回 {"name": "b", "company": "company2"} 而不是整行。
I can only think of unnesting the array and the return the element from that:我只能想到取消嵌套数组并从中返回元素:
SELECT x.j
FROM company c
cross join jsonb_array_elements(c.companyjson) as x(j)
where x.j = '{"company": "company2" , "name": "b"}'
You can directly return the first component through companyJson -> 0
which contains ->
operand returning the first component by argument zero :您可以通过companyJson -> 0
直接返回第一个组件,其中包含->
操作数通过参数零返回第一个组件:
SELECT companyJson -> 0 as companyJson
FROM company
WHERE companyJson @> '[{"company": "company2" , "name": "b"}]';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.