我有一张桌子t1
id | names
----|-------------------------
1 | {jully , alex , sarah}
2 | {bety , cate , jenifer}
3 | {adam , pit , joee}
4 | {piter , mat , andy}
所以,我需要行至少有一个以“a”开头的名称,我需要的结果如下所示
在第1行:亚历克斯
在第3行:亚当
在第4行:安迪
id | names
-----|-------------------------
1 | {jully , alex , sarah}
3 | {adam , pit , joee}
4 | {piter , mat , andy}
这样的查询
select * from t1 where 'a' like% any t1.name
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}
还有另一个使用unnest
的解决方案
select * from t1
where exists (
select * from unnest(t1.names) n
where n like 'a%')