分隔符字段轉多列查詢
背景
在開發中,有可能會遇到數據庫一個字段存儲了由分隔符分割的多個字符串,而我們需要將這些分割的字符串轉為多列進行封裝,下面是如何通過sql直接實現的例子。
建表test
create table test
(
id varchar(30) not null,
name varchar(30) null,
depts varchar(255) null,
constraint test_pk
primary key (id)
);
插入數據
insert into test
values ('demo', 'Demo Group',
'感染性疾病科室(南院區)/心臟內一科門診(南院區)/婦產藥房/兒科藥房/急診藥房/門診西藥房/門診中藥房/中草藥庫/西成藥庫/中藥煎藥室')
, ('Inpatient', 'Inpatient Admission', '心臟內一科門診(南院區)')
, ('innurse', 'innurse', '心臟內一科門診(南院區)')
, ('med', 'med manager', '門診部/病案室/醫務科/病案室/門診收費處(北院區)/醫務科/醫務科');

sql查詢的思路是使用一張指針表配合函數substring_index實現
新建指針表
create table s_split_index
(
id int
);
插入指針數據
insert into s_split_index
values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16);
sql實現
SELECT
a.`user_id`,
substring_index( substring_index( a.`depts`, '/', b.`id` + 1 ), '/',- 1 ) AS dept_id
FROM
( SELECT `depts`, `id` AS user_id FROM test) AS a
JOIN `s_split_index` AS b ON b.`id` < ( char_length( a.`depts` ) - char_length( REPLACE ( a.`depts`, '/', '' ) ) + 1 )
order by user_id;
這條sql是利用指針表先分割出左邊的字符串部分,然后再利用指針-1取出右邊的一個字符串以達到分割的目的。


浙公網安備 33010602011771號