regexp_split_to_table和regexp_split_to_array实例

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

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

-- f_interest 兴趣,多个兴趣逗号分割
CREATE TABLE open.t_ttt
(
    f_user_name character varying(20) NOT NULL,
    f_interest character varying(100),
    CONSTRAINT t_ttt_pkey PRIMARY KEY (f_user_name)
);
-- 数据
INSERT INTO open.t_ttt(f_user_name, f_interest) VALUES ('张三', '足球,篮球,羽毛球');
INSERT INTO open.t_ttt(f_user_name, f_interest) VALUES ('李四', '篮球,排球');

-- 如果要查询兴趣包含“篮球”的用户列表,可以使用 regexp_split_to_table 函数:
select
    t.f_user_name,
    t.tab_interest
from (
    select f_user_name, regexp_split_to_table(f_interest, ',') as tab_interest from t_ttt
) t
where t.tab_interest = '篮球';

 f_user_name | tab_interest
-------------+--------------
 李四        | 篮球
 张三        | 篮球

-- 如果要查询每个用户的第一个兴趣,可以使用 regexp_split_to_array 函数:
select
    t.f_user_name,
    t.arr_interest[1]
from (
    select f_user_name,regexp_split_to_array(f_interest, ',') as arr_interest from t_ttt
) t;

 f_user_name | arr_interest
-------------+--------------
 李四        | 篮球
 张三        | 足球

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值