Postgres JSONB从数据数组中进行选择

时间:2016-05-03 16:50:04

标签: sql json postgresql jsonb

我正在使用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"}]

正如您所看到的,这不支持查询不完整的字符串。

谢谢!

1 个答案:

答案 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
;