Create MySQL Split String Function SPLIT_STR fedecarg.com/…/mysql-split-string-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, '');
Run SQL:
SELECT t.en AS `type`, SPLIT_STR(l.en, ',', 1) AS city,
SPLIT_STR(l.en, ',', 2) AS country
FROM table1
JOIN table2
USING ( id )
LEFT JOIN table3 AS t ON table1.type = t.id
/* the next line has failure with SPLIT_STR */
LEFT JOIN table3 AS l ON table1.location = l.id
WHERE language.lang = 'en'
AND language.url = 'europe-countries'
LIMIT 1;
table1
id | type | location
-----------------+-----------------+-----------------
6BC45C02 | place | london,england
table2
id | url
-----------------+-----------------
6BC45C02 | europe-countries
table3
id | en
-----------------+-----------------
london | London
england | England
Failed result:
type | city | country
-----------------+-----------------+----------------
place | NULL | NULL
Expected result would be to return city and country:
type | city | country
-----------------+-----------------+-----------------
place | London | England
On checking if SPLIT_STR is working with simple SQL:
SELECT SPLIT_STR(location, ',', 1) AS city, SPLIT_STR(location, ',', 2) AS contry
FROM table1
WHERE id = '6BC45C02'
LIMIT 1;
it returns fine result:
city | contry
-----------------+-----------------
london | england
Maybe this… but performance will be terrible.
This would be better as it doesn’t require calling the function 4 times: (used coalesce to determine if function isn’t working as expected will return proper case, then lower case, then function broke if it’s not working as expected)
Still better exists: is table 3’s only purpose to Proper case the city/country name; and is the only purpose of the UDF (user defined function) to split the values?
join.
you)