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