PostgreSQL 字符串分隔函数(regexp_split_to_table、regexp_split_to_array)  发表于 2020-06-01 |  阅读次数: 394

转载:https://zhangzw.com/posts/20200601.html

 

PostgreSQL 字符串分隔函数(regexp_split_to_table、regexp_split_to_array)

 发表于 2020-06-01 |  阅读次数: 394

PostgreSQL 数据库提供 regexp_split_to_table 和 regexp_split_to_array 两个函数用于分隔字符串成表和数组,在某些场景下使用起来还挺方便的。

举个例子:有这样一张表,维护用户的兴趣,多个兴趣用逗号分隔。

1
2
3
4
5
6
7
8
9
10
-- 表结构 
CREATE TABLE public.t_user
(
    user_name character varying(20) NOT NULL, -- 用户姓名 
    interest character varying(100), -- 兴趣,多个兴趣都好分割 
    CONSTRAINT t_user_pkey PRIMARY KEY (user_name)
);
-- 数据 
INSERT INTO public.t_user(user_name, interest) VALUES ('张三', '足球, 篮球, 羽毛球');
INSERT INTO public.t_user(user_name, interest) VALUES ('李四', '篮球, 排球');

1591005481682

如果要查询兴趣包含“篮球”的用户列表,可以使用 regexp_split_to_table 函数:

1
2
3
4
5
6
7
select
    t.user_name,
    t.tab_interest
from (
    select user_name, regexp_split_to_table(interest, ',') as tab_interest from t_user
) t
where t.tab_interest = '篮球';

1591005519646

如果要查询每个用户的第一个兴趣,可以使用 regexp_split_to_array 函数:

1
2
3
4
5
6
select
    t.user_name,
    t.arr_interest[1]
from (
    select user_name, regexp_split_to_array(interest, ',') as arr_interest from t_user
) t

1591005548544

总结

regexp_split_to_table 和 regexp_split_to_array 都是字符串分隔函数,可通过指定的表达式进行分隔。区别是 regexp_split_to_table 将分割出的数据转成行,regexp_split_to_array 是将分隔的数据转成数组。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值