0

提前致谢。假设,我有一个表,其中包含类似这样的数组中的值。

CREATE TABLE example (
    id serial4 NOT NULL,
    name varchar(100) NOT NULL,
    content_type json NULL
    CONSTRAINT example_pkey PRIMARY KEY (id)
);
id |name |content_type
-----------------------
 1 | P   | ['a','b','c']
 2 | Q   | ['a',]
 3 | R   | ['b','c']
 4 | S   | ['a','c']

我想查找'c'content_type 中包含的行

我已经尝试过,但无法获得,

select * from table where ARRAY['c'] && content_type;

有人帮我建立查询吗?

4

1 回答 1

2

更新了将列类型从 text[] 更改为 json

如果您的列类型是 JSON,您可以使用两种方案:

演示

  1. 转换为jsonb并使用?运算符(Postgres 文档
select * from test where content_type::jsonb ? 'c';
  1. 利用json_array_elements_text
select distinct on(t.id) t.*
from 
  test t
  cross join json_array_elements_text(content_type) je
where
  je.value = 'c';

旧场景

您可以使用any函数来检查数组中是否存在值或根据Postgres 文档使用数组运算符@>

演示

  1. any
select * from test where 'c' = any(content_type);
  1. @>
select * from test where content_type @> array['c'];
于 2021-12-01T09:51:17.047 回答