좀 조잡하긴 하지만 이것저것 참고해서 만들어봤습니다...
https://stackoverflow.com/questions/14950466/how-to-split-the-name-string-in-mysql
https://stackoverflow.com/questions/7020001/how-to-count-items-in-comma-separated-list-mysql
DELIMITER $$ DROP FUNCTION IF EXISTS split_str$$ DROP FUNCTION IF EXISTS myfunc$$ CREATE FUNCTION SPLIT_STR(x VARCHAR(255), delim VARCHAR(12), pos INT) RETURNS VARCHAR(255) RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos), LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, ''); $$ CREATE FUNCTION myfunc (s1 VARCHAR(20)) RETURNS VARCHAR(20) BEGIN DECLARE returnVal VARCHAR(20); DECLARE nCnt INT DEFAULT 0; CREATE TEMPORARY TABLE myfunc_tab (n99 int); WHILE (nCnt < LENGTH(s1) - LENGTH(REPLACE(s1, ',', '')) + 1 ) DO SET nCnt = nCnt + 1; INSERT INTO myfunc_tab VALUES(split_str(s1,',',nCnt)); END WHILE; SELECT group_concat(n99 order by n99) INTO returnVal FROM myfunc_tab; DROP TEMPORARY TABLE myfunc_tab; RETURN returnVal; END $$ DELIMITER ; MariaDB [test]> select myfunc ('1,2,5,4,3,6'); +------------------------+ | myfunc ('1,2,5,4,3,6') | +------------------------+ | 1,2,3,4,5,6 | +------------------------+ 1 row in set (0.001 sec)
UNION 이 입력값에 대한 UNION 이 아닙니다.
입력값 '1,2,5,4,3,6' 은 따로 있습니다.
자세히 보세요.
-- 명확하게 구별하기 위해 입력값을 아래로 내려 봤습니다. SELECT GROUP_CONCAT(v ORDER BY v) v -- 출력값 FROM (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(v, ',', lv), ',', -1) + 0 v FROM (SELECT '1,2,5,4,3,6' v) a -- 입력값 , (SELECT 1 lv UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 ) b ) c ;
-- 테이블 직접 조회 예시 -- WITH t AS ( SELECT 1 idx, '1,2,5,4,3,6' v UNION ALL SELECT 2, '11,22,5,6,3,9' ) SELECT idx, v , GROUP_CONCAT(x ORDER BY x) x FROM (SELECT idx, v , SUBSTRING_INDEX(SUBSTRING_INDEX(v, ',', lv), ',', -1) + 0 x FROM t a , (SELECT 1 lv UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 ) b ) c GROUP BY idx, v ;