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"}]';
上述程序的输出为
2 [{"name": "b", "company": "company2"}, {"name": "b", "company": "company3"}]
无论如何要返回{"名称": "b", "公司": "company2"} 而不是整行。
我只能想到取消嵌套数组并从中返回元素:
SELECT x.j
FROM company c
cross join jsonb_array_elements(c.companyjson) as x(j)
where x.j = '{"company": "company2" , "name": "b"}'
你可以通过包含companyJson -> 0
->
操作数直接返回第一个组件,其中包含通过参数零返回第一个组件的操作数:
SELECT companyJson -> 0 as companyJson
FROM company
WHERE companyJson @> '[{"company": "company2" , "name": "b"}]';
演示