SELECT
result,
LENGTH(GROUP_CONCAT(file_path)) - LENGTH(REPLACE(GROUP_CONCAT(file_path), result, '')) AS qty
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(file_path, ',', a.letter + 1), ',', -1) result,
file_path
FROM book
INNER JOIN (SELECT 0 letter UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) a ON LENGTH(REPLACE(file_path, ',' , '')) <= LENGTH(file_path) - a.letter
) a
GROUP BY result
HAVING COUNT(result) > 0 AND result <> ''
ORDER BY result
CREATE TABLE table1
(`id` int, `value` varchar(20))
;
INSERT INTO table1
(`id`, `value`)
VALUES
(1, 'Red,Green,Blue'),
(2, 'Orangered,Periwinkle'),
(3, 'Green,Blue,Orangered'),
(4, 'Red,Blue')
;
DELIMITER $$
DROP PROCEDURE IF EXISTS explode_table $$
CREATE PROCEDURE explode_table(bound VARCHAR(255))
BEGIN
DECLARE id INT DEFAULT 0;
DECLARE value TEXT;
DECLARE occurance INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE splitted_value TEXT;
DECLARE done INT DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT table1.id, table1.value
FROM table1
WHERE table1.value != '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
DROP TEMPORARY TABLE IF EXISTS table2;
CREATE TEMPORARY TABLE table2(
`id` INT NOT NULL,
`value` VARCHAR(255) NOT NULL
) ENGINE=Memory;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO id, value;
IF done THEN
LEAVE read_loop;
END IF;
SET occurance = (SELECT LENGTH(value)
- LENGTH(REPLACE(value, bound, ''))
+1);
SET i=1;
WHILE i <= occurance DO
SET splitted_value =
(SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(value, bound, i),
LENGTH(SUBSTRING_INDEX(value, bound, i - 1)) + 1), ',', ''));
INSERT INTO table2 VALUES (id, splitted_value);
SET i = i + 1;
END WHILE;
END LOOP;
SELECT t.value `สี`, COUNT(t.value) `จำนวน` FROM (SELECT * FROM table2) t GROUP BY t.value;
CLOSE cur1;
END; $$
-- เวลาเรียกใช้
CALL explode_table(',');