简体   繁体   English

在 postgres json 数组中查找单个元素

[英]Finding a single element in postgres json array

I have a table that has a Json typed column and I am trying query that table based of values that are contained in that json column.我有一个具有 Json 类型列的表,我正在尝试根据该 json 列中包含的值查询该表。

Here is the relevant DDL:这是相关的DDL:

create table user
(
    roles json
);

Here is what a roles value would look like:下面是角色值的样子:

[70,254]

I want to be able to perform a query like this:我希望能够执行这样的查询:

select * from user where roles in(254);

So I've tried this:所以我试过这个:

SELECT * from apptree.atf_app_user where roles @> 254;

And it is giving me this error:它给了我这个错误:

[2017-12-01 14:58:16] [42883] ERROR: operator does not exist: json @> integer
[2017-12-01 14:58:16] Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
[2017-12-01 14:58:16] Position: 48

The operator @> works on jsonb arguments.运算符@> 适用于 jsonb 参数。 Cast the column to jsonb:将列转换为 jsonb:

select * 
from apptree.atf_app_user 
where roles::jsonb @> '254';

Update.更新。 There is no operator to search in a json array for any of multiple values.没有运算符可以在 json 数组中搜索多个值中的任何一个。 You can use the function json_array_elements_text(), eg:您可以使用函数json_array_elements_text(),例如:

select t.* 
from apptree.atf_app_user t
cross join json_array_elements_text(roles)
where value in ('70', '71');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM