Last active
October 3, 2017 09:21
-
-
Save jackhftang/fefb574c0d339f87e860038d29096f82 to your computer and use it in GitHub Desktop.
mysql procedure for counting comma delimited varchar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- base table | |
CREATE TABLE IF NOT EXISTS tags ( | |
id INT PRIMARY KEY AUTO_INCREMENT, | |
tags VARCHAR(128) | |
); | |
-- prepare data | |
INSERT INTO tags(tags) VALUES (",3,47,1,5,"), ("1,2,3"), (",4,5,6,7"), ("3,4,6,"); | |
-- create procedure | |
DROP PROCEDURE IF EXISTS tag_cnt; | |
DELIMITER // | |
CREATE PROCEDURE tag_cnt() | |
BEGIN | |
DECLARE ts VARCHAR(128); | |
DECLARE done INT DEFAULT FALSE; | |
DECLARE cur CURSOR FOR SELECT concat(',', tags, ',') FROM tags; | |
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; | |
OPEN cur; | |
-- create temp table for counting | |
CREATE TEMPORARY TABLE IF NOT EXISTS tag_cnt ( | |
tag VARCHAR(128) PRIMARY KEY, | |
cnt INT DEFAULT 0 | |
); | |
-- clear table | |
TRUNCATE TABLE tag_cnt; | |
each_row: LOOP | |
FETCH cur INTO ts; | |
IF done THEN LEAVE each_row; END IF; | |
SET @start = locate(',', ts); | |
each_field: LOOP | |
SET @end = locate(',', ts, @start + 1); | |
-- no more tag | |
IF @end = 0 THEN LEAVE each_field; END IF; | |
IF @end <> @start+1 THEN | |
SET @t = trim( substring(ts, @start + 1, @end - @start -1) ); | |
INSERT INTO tag_cnt SET tag = @t ON DUPLICATE KEY UPDATE cnt = cnt + 1; | |
END IF; | |
SET @start = @end; | |
END LOOP each_field; | |
END LOOP each_row; | |
CLOSE cur; | |
END | |
// | |
DELIMITER ; | |
CALL tag_cnt(); | |
SELECT * FROM tag_cnt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment