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_inter

本文介绍了如何利用PostgreSQL的regexp_split_to_table和regexp_split_to_array函数,处理用户兴趣表中的逗号分隔数据,实现按兴趣筛选和获取用户首兴趣。这些函数在数据库操作中提供了高效的数据解析能力。
最低0.47元/天 解锁文章
1615

被折叠的 条评论
为什么被折叠?



