-3

I have a column in my database name location which have city name and country name in this format New york,America. I want to run a select query with the explode function like which we use in php to separate values like this so that i can get comma , separated values

select explode(",",location) from address;

Also with the alias of city column holding New York and alias of country holding value of America. So that i can use them in my store procedure and insert this values in references table in the columns city and country

5 Answers5

4

You can not really "explode" or split on all comma's, but you can split a string on any comma using SUBSTRING_INDEX.

SELECT SUBSTRING_INDEX('New york,America', ',', 1);
-> New york
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
1

Use Group concat

   SELECT GROUP_CONCAT( location )
    FROM `address`
Suraj
  • 363
  • 2
  • 16
1
CREATE FUNCTION strSplit(x varchar(255), delim varchar(12), pos int)  
returns varchar(255)
return replace(substring(
  substring_index(x, delim, pos+1), 
  length(substring_index(x, delim, pos)) + 1
), delim, '');


select strSplit("aaa,b,cc,d", ',', 1) as second;
> b
vp_arth
  • 14,461
  • 4
  • 37
  • 66
0

You can also select the row and store it as a string, and use the explode function to separate the values if you are intending to use the function itself.

Everett
  • 35
  • 4
0

Assuming that exploding will be to create N number of rows, then you can do it like this.

SET @completeString = "Hola,New york,America,!,";
SET @divider = ",";

WITH RECURSIVE strings(m) AS (
    SELECT
        @completeString
    UNION ALL
    SELECT
        SUBSTRING(m, INSTR(m, @divider)+ 1)
    FROM
        strings
    WHERE
        INSTR(m, @divider)!= 0
)
SELECT
    SUBSTRING_INDEX(m, @divider, 1) exploted_strings
FROM
    strings;

That'll give you five rows, including the empty string

+----------------+
|exploted_strings|
+----------------+
| Hola           |
| New york       |
| America        |
| !              |
|                |
+----------------+

Or have it in a Procedure.

CREATE PROCEDURE explode(IN completeString TEXT, IN divider TEXT)
BEGIN
    WITH RECURSIVE strings(m) AS (
        SELECT 
            completeString
        UNION ALL
        SELECT 
            SUBSTRING(m, INSTR(m, divider)+ 1)
        FROM 
            strings 
        WHERE 
            INSTR(m, divider)!= 0
)
SELECT
    SUBSTRING_INDEX(m, divider, 1)
    FROM strings;
END

And call it like

CALL explode ("Hola,New york,America,!,",",");