Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array data type, split string,

Tags:

mysql

I'm currently working on a function in MYSQL, I have a comma delimited string (1,22,344,55) from another table, How can I split this in MYSQL to an array (NOT temp_table). Also, is there a similar function in MYSQL where I can do foreach()?

like image 624
gumpi Avatar asked Nov 02 '10 14:11

gumpi


2 Answers

MySQL does not include a function to split a delimited string. However, it’s very easy to create your own function.

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

Usage

SELECT SPLIT_STR(string, delimiter, position)

From here: http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/

like image 185
Roman Goyenko Avatar answered Nov 16 '22 00:11

Roman Goyenko


The correct usage in MySQL is:

SELECT FIND_IN_SET('b','a,b,c,d');

Gives as result: 2

like image 20
Luxo Mansilla Avatar answered Nov 15 '22 23:11

Luxo Mansilla