简体   繁体   中英

How to turn a single row to multiple row in mysql?

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

View on DB Fiddle

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.

first, to show all content of your table, u can use * (it's mean all)

SELECT * FROM <TableName>;

在此处输入图像描述

for spesific column u can change it to column name,

SELECT <ColumnName> FROM <TableName>;

Ex: in my case i want show just content of name. so i can write

SELECT name FROM users;

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM