ex:
the column 'genre' has a row of data:
+----------------------------+
| genres |
+----------------------------+
| action, adventure, drama | |
| |
+----------------------------+
my desired output will be a column that holds the following data:
+------------+
| genre |
+------------+
| action |
| adventure |
| drama |
+------------+
how do I do it in mysql?
You can try to create a split function as below to get your expectation part of values by comma.
Schema (MySQL v5.7)
DELIMITER $$
DROP FUNCTION IF EXISTS `SPLIT_STR` $$
CREATE FUNCTION `SPLIT_STR`(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
) RETURNS varchar(255) CHARSET latin1
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '') $$
DELIMITER ;
then use UNION ALL
to combine those result as below
Query #1
SELECT SPLIT_STR(genres, ',', 1) genre FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 2) FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 3) FROM T;
genre |
---|
action |
adventure |
drama |
NOTE
I would suggest you re-design your table scheme because it was bad for store value by comma and you need to convert as rows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.