我正在使用Postgres数据库而我正在尝试使用新的JSONB类型。我有一个名为employees
的表,其中包含一个名为previous_companies
的列,其中包含以下JSON数据:
[{"company":"Facebook", "link": "www.facebook.com"}, {"company":"Google", "link": "www.google.com"}, {"company":"Some Face", "link": "www.someface.com"}]
我正在尝试为“公司”字段选择具有特定字符串的所有员工,例如:
[{"company":"Facebook", "link": "www.facebook.com"}, {"company":"Some Face", "link": "www.someface.com"}]
我能够对EXACT字符串进行查询,如下所示:
SELECT * FROM employees WHERE previous_companies @> '[{"company":"Facebook"}]'
但它会返回:[{"company":"Facebook", "link": "www.facebook.com"}]
正如您所看到的,这不支持查询不完整的字符串。
谢谢!
答案 0 :(得分:4)
jsonb_array_elements()
函数可能有助于按数组JSONB列进行查询:
SELECT
id,
to_jsonb(array_agg(previous_company)) AS previous_companies
FROM (
SELECT
id,
jsonb_array_elements(previous_companies) AS previous_company
FROM ( VALUES
('id1', '[{"company":"Facebook", "link": "www.facebook.com"},{"company":"Google", "link": "www.google.com"}, {"company":"Some Face", "link": "www.someface.com"}]'::jsonb),
('id2', '[{"company":"Some Face", "link": "www.someface.com"}]'::jsonb),
('id3', '[{"company":"Google", "link": "www.google.com"}]'::jsonb)
) employees (id, previous_companies)
) T
WHERE
lower(previous_company->>'company') LIKE '%face%'
GROUP BY
id
;