您可以这样做:http://www.sqlfiddle.com/#!1/5c148/12
select *
from tbl
where translate(ids, '[]','{}')::int[] && array[5];
输出:
| ID | IDS |
--------------
| 2 | [3,5] |
也可以使用 bool_or:http://www.sqlfiddle.com/#!1/5c148/11
with a as
(
select id, unnest(translate(ids, '[]','{}')::int[]) as elem
from tbl
)
select id
from a
group by id
having bool_or(elem = 5);
查看原始元素:
with a as
(
select id, unnest(translate(ids, '[]','{}')::int[]) as elem
from tbl
)
select id, '[' || array_to_string(array_agg(elem), ',') || ']' as ids
from a
group by id
having bool_or(elem = 5);
输出:
| ID | IDS |
--------------
| 2 | [3,5] |
Postgresql DDL 是原子的,如果在您的项目中还不晚,只需将您的字符串类型数组构造成一个真实数组:http://www.sqlfiddle.com/#!1/6e18c/2
alter table tbl
add column id_array int[];
update tbl set id_array = translate(ids,'[]','{}')::int[];
alter table tbl drop column ids;
查询:
select *
from tbl
where id_array && array[5]
输出:
| ID | ID_ARRAY |
-----------------
| 2 | 3,5 |
您也可以使用包含运算符:http://www.sqlfiddle.com/#!1/6e18c/6
select *
from tbl
where id_array @> array[5];
我更喜欢&& 语法,它直接表示交集。它反映您正在检测两个集合之间是否存在交集(数组是一个集合)
http://www.postgresql.org/docs/8.2/static/functions-array.html