PostgreSQL 數據庫提供 regexp_split_to_table 和 regexp_split_to_array 兩個函數用於分隔字符串成表和數組,在某些場景下使用起來還挺方便的。
舉個例子:有這樣一張表,維護用戶的興趣,多個興趣用逗號分隔。
-- 表結構 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 ('李四', '籃球, 排球');
如果要查詢興趣包含“籃球”的用戶列表,可以使用 regexp_split_to_table 函數:
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 = '籃球';
如果要查詢每個用戶的第一個興趣,可以使用 regexp_split_to_array 函數:
select t.user_name, t.arr_interest[1] from ( select user_name, regexp_split_to_array(interest, ',') as arr_interest from t_user ) t
總結
regexp_split_to_table 和 regexp_split_to_array 都是字符串分隔函數,可通過指定的表達式進行分隔。區別是 regexp_split_to_table 將分割出的數據轉成行,regexp_split_to_array 是將分隔的數據轉成數組。
https://zhangzw.com/posts/20200601.html