Split column into multiple rows (split)

Asked

Viewed 1,533 times

1

I have a table cidade_bairro with several cities and neighborhoods. I want to transfer this data to a new table, but in several lines instead of being in one.

EX:

Cidade  Bairros<br>
SP |    Consolação-Morumbi-Saude

In the new table "city_bairro2" would be separated into 3 lines:

Cidade  Bairro
SP |    Consolação
SP | Morumbi
SP | Saude

Could someone help me perform this transfer via SQL Mysql?

1 answer

2


You can create a support table with the number maximum separations that neighborhoods can have. More or less as follows:

CREATE TABLE numeros (
  numero int
);

INSERT INTO numeros(numero)
VALUES(1), (2), (3), (4), (5),
      (6), (7), (8), (9), (10);

And use the following query to extract the data:

SELECT DISTINCT cb.cidade,
                SUBSTRING_INDEX(SUBSTRING_INDEX(cb.bairros, '-', n.numero), '-', -1) AS bairro
  FROM cidade_bairro cb
       CROSS JOIN numeros n
 ORDER BY cb.cidade, n.numero;

Note that the DISTINCT will filter the same results.

You can check the result on SQL Fiddle.


You can achieve the maximum number of occurrences of - in your table with the query next:

SELECT MAX(ROUND((LENGTH(cb.bairros) - LENGTH(REPLACE(cb.bairros, '-', ''))) / LENGTH('-'))) + 1 AS quantidade
  FROM cidade_bairro cb

References:

  • This table has thousands of lines, which makes it difficult to define the value "n" for each of the lines

  • @Enter the maximum size in the table numeros. It doesn’t have to be the exact amount. If you think the maximum is going to be 500 neighborhoods in a city, put 500 numbers there. Spending a little bit won’t hurt, it only hurts a little performance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.