postgresql搜索文本到文本数组

时间:2017-03-04 13:13:56

标签: arrays postgresql sql-like any

我有一张桌子t1

id  |  names
----|-------------------------
1   |  {jully , alex , sarah}
2   |  {bety , cate , jenifer}
3   |  {adam , pit , joee}
4   |  {piter , mat , andy}

所以,我需要的行至少有一个以" a"开头的名字。 我需要的结果在下面

在第1行:alex

第3行

:adam

第4行

:andy

id   |   names
-----|-------------------------
1    |  {jully , alex , sarah}
3    |  {adam , pit , joee}
4    |  {piter , mat , andy}

像这样的查询

select * from t1 where 'a' like% any t1.name

3 个答案:

答案 0 :(得分:3)

select *
from (
    select id, unnest(names) as name
    from t
) s
where name like 'a%';
 id | name 
----+------
  1 | alex
  3 | adam
  4 | andy

汇总它:

select id, array_agg(name)
from (
    select id, unnest(names) as name
    from t
) s
where name like 'a%'
group by id;
 id | array_agg 
----+-----------
  4 | {andy}
  1 | {alex}
  3 | {adam}

答案 1 :(得分:1)

使用unnest

的另一种解决方案
select * from t1
where exists (
  select * from unnest(t1.names) n
  where n like 'a%')

答案 2 :(得分:0)

如果必须在文本数组内搜索多个值。您可以使用:

SELECT * FROM t1 WHERE names && ARRAY['alex', 'jully'] ;
相关问题