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 是将分隔的数据转成数组。

猜你喜欢

转载自blog.csdn.net/ww_ndsc_ww/article/details/107971499