2020. 11. 6. 07:26ㆍ공유
CREATE TABLE tablename (
id INT,
name VARCHAR(20));
INSERT INTO tablename VALUES
(1, 'a,b,c'),
(2, 'd');
CREATE TABLE numbers (
n INT PRIMARY KEY);
INSERT INTO numbers VALUES (1),(2),(3),(4),(5),(6);
If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:
SELECT
tablename.id, SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
FROM
numbers INNER JOIN tablename
ON CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
ORDER BY
id, n
If you cannot create a table, then a solution can be this:
select tablename.id, SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name from (select 1 n union all select 2 union all select 3 union all select 4 union all select 5) numbers INNER JOIN tablename on CHAR_LENGTH(tablename.name) -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1 order by id, n
solution2 can be use the "WITH" clause :
WITH RECURSIVE numbers AS
(
SELECT 1 AS n
UNION
SELECT n+1 AS n FROM numbers WHERE n<10
)
SELECT
tablename.id, SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
FROM
numbers INNER JOIN tablename
ON CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
ORDER BY
id, n
'공유' 카테고리의 다른 글
코로나19 특고 프리랜서 고용안정지원금 (0) | 2020.11.06 |
---|---|
2차 재난지원금 신청방법 지원대상 (0) | 2020.11.06 |
일출 일몰 시간 방향 지도 (1) | 2020.11.06 |
JBoss multiple instance (0) | 2018.08.21 |
MySql 에서 Oracle nextval 구현 (0) | 2017.12.04 |