Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JOIN & Split String

Tags:

string

join

mysql

I want to JOIN two table. Have no problem with that. I have problem with quite different thing.

Here's my code:

SELECT * FROM `table1`
JOIN `table2` ON `table1.`field`=`table2`.`field`
...

The main issue is that table1.field is a string, comma-separated. Is there any good and fast way to split it?

Update
I found a function by Federico Cagnelutti

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('a|bb|ccc|dd', '|', 3) as third;

Quite useful but it requires position integer as third parameter. Anyway, I do not know the amount of comma-separated words. Bascially, it's up to 20 words, but I don't know how many.

Update 2 To clarify my question. Here's what I like to have (I know the following query is incorrect):

SELECT * FROM `table1`
JOIN `table2` ON `table2`.`id` IN (`table1`.`field`)

Update 3
Example strings: table1.field = '202, 185, 505', table2.field = 202

like image 890
Tom Avatar asked Mar 09 '26 06:03

Tom


1 Answers

I'm not sure I understand exactly what you need, but perhaps you could use the FIND_IN_SET function?

SELECT * FROM `table1`
JOIN `table2` ON FIND_IN_SET( `table2`.`field`, `table1.`field` ) > 0

Performance might be a problem with this though.

Update:

If you have leading spaces in the data, as in the sample given, this could be handled with REPLACE. This wouldn't work where there are embedded spaces, but would cater for cases where there are sometimes leading spaces and sometimes not. Example:

SELECT  *
FROM    table1 t1
JOIN    table2 t2
ON      FIND_IN_SET( t2.field, REPLACE( t1.field, ' ', '' ) ) > 0

There is a limit of 64 members in a set, so if the comma-separated string is long this will break.

like image 133
martin clayton Avatar answered Mar 11 '26 21:03

martin clayton