Создание функции MySQL Split String 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, '');
Выполнить 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
Таблица3
id | en
-----------------+-----------------
london | London
england | England
Неудачный результат:
type | city | country
-----------------+-----------------+----------------
place | NULL | NULL
Ожидаемый результат будет возвращать city
и country
:
type | city | country
-----------------+-----------------+-----------------
place | London | England
При проверке, работает ли SPLIT_STR
с простым SQL:
SELECT SPLIT_STR(location, ',', 1) AS city, SPLIT_STR(location, ',', 2) AS contry
FROM table1
WHERE id = '6BC45C02'
LIMIT 1;
возвращает прекрасный результат:
city | contry
-----------------+-----------------
london | england