首页 > 解决方案 > 如何从具有 json 列条件的表中进行选择?

问题描述

contact_information在 PostreSQL 9.6 有一张桌子。

CREATE TABLE contact_information
(
  employee_id UUID NOT NULL PRIMARY KEY,
  messengers JSON NOT NULL
);

INSERT INTO contact_information 
  (employee_id, messengers) 
VALUES 
  ('8b5fbfec-d213-426c-86fa-4fda5f586319', '[{"Type":"skype","IDs":["some skype id","another skype id"]}]');

我需要选择 ID 包含子字符串的所有employee_id,例如“id ILIKE '%other%'”。

我尝试了什么:

SELECT
  ci.employee_id,
  json_array_elements(json_array_elements(ci.messangers)->'IDs'::text)::text AS ids
FROM contact_information AS ci

并得到:

3ba6feba-ff81-11e4-9408-984be16afda1    "some skype id"
3ba6feba-ff81-11e4-9408-984be16afda1    "another skype id"

但我不能添加到语句 WHERE ids ILIKE '%other%' - 列 ID 不存在。

如果我正在尝试

SELECT
  ci.employee_id
FROM contact_information AS ci
WHERE json_array_elements(json_array_elements(ci.messangers)->'IDs'::text)::text ILIKE '%other%'

得到:错误:在 WHERE 中不允许设置返回函数。

有什么想法可以解决这个问题吗?

标签: jsonpostgresql

解决方案


解决了:

SELECT DISTINCT t.employee_id 
FROM (
  SELECT
    ci.employee_id,
    json_array_elements(json_array_elements(ci.messangers)->'IDs'::text)::text AS ids
  FROM contact_information AS ci
) as t
WHERE t.ids ILIKE '%other%'

对不起一个愚蠢的问题=(


推荐阅读