[英]How to query array in Postgres json column?
Thanks in advance.提前致谢。 Assume, I have a table that contains the value in an array something like this.
假设,我有一个表,其中包含类似这样的数组中的值。
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']
I want to find which row contains 'c'
in content_type我想在 content_type 中查找哪一行包含
'c'
I have tried but couldn't get,我已经尝试过,但无法获得,
select * from table where ARRAY['c'] && content_type;
Is there someone to help me to build the query?有人帮我建立查询吗?
Updated for change column type from text[] to json更新了将列类型从 text[] 更改为 json
If your column type is JSON you can use two scenarios:如果您的列类型是 JSON 您可以使用两种方案:
?
?
operator ( Postgres document )select * from test where content_type::jsonb ? 'c';
json_array_elements_text
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';
Old scenario旧场景
You can use any
function to check values exist in an array or according to Postgres document use array operator @>
您可以使用
any
function 来检查数组中是否存在值或根据Postgres 文档使用数组运算符@>
any
any
select * from test where 'c' = any(content_type);
@>
@>
select * from test where content_type @> array['c'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.