SQL >> Base de Datos >  >> RDS >> Mysql

Convertir una fila en varias filas en MySQL

Para un ID concreto, puedes despivotar con una serie de UNION ALL:

select id, city_name from ( select id, city_1 as city_name from yourTable union all select id, city_2 from yourTable union all select id, city_3 from yourTable union all select id, city_4 from yourTable ) as t where id = yourID

Pruébalo aquí

Y para aplicarlo a toda la tabla, simplemente quita el filtro y ordena por id:

select id, city_name from ( select id, city_1 as city_name from yourTable union all select id, city_2 from yourTable union all select id, city_3 from yourTable union all select id, city_4 from yourTable ) as t order by id

Esta es una forma práctica de normalizar una fila que empaqueta varias columnas de ciudad en un diseño de una fila por ciudad.