创建MySQL拆分字符串函数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;
表1
id | type | location
-----------------+-----------------+-----------------
6BC45C02 | place | london,england
表2
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
答案 0 :(得分:1)
也许这......但表现会很糟糕。
SELECT T1.type,
SPLIT_STR(t.en, ',', 1) AS city,
SPLIT_STR(l.en, ',', 2) AS country
FROM table1 t1
INNER JOIN table2 t2
ON T1.ID = T2.ID
LEFT JOIN table3 t
ON t.id = SPLIT_STR(t1.location, ',', 1)
LEFT JOIN table3 l
ON l.id = SPLIT_STR(t1.location, ',', 2)
WHERE t2.url = 'europe-countries'
LIMIT 1;
这样会更好,因为它不需要调用函数4次:(使用coalesce来确定函数是否按预期工作将返回正确的情况,然后是小写,然后如果函数没有按预期工作则函数会中断)
SELECT InTable.Type,
coalesce(t.en, inTable.City, 'FunctionBroke') as city,
coalesce(l.en, intable.country, 'FunctionBroke2') as country
FROM
(SELECT t1.type,
SPLIT_STR(T1.Location, ',', 1) AS City,
SPLIT_STR(T1.Location, ',', 2) AS Country
FROM table1 T1
INNER JOIN table2 T2
ON T1.ID = T2.ID
AND t2.url='europe-countries'
) InTable
LEFT JOIN table3 t
ON InTable.City = t.id
LEFT join table3 l
ON InTable.Country = l.id
LIMIT 1;
更好的存在:表3的唯一目的是正确判断城市/国家名称;并且是UDF(用户定义函数)分割值的唯一目的吗?
答案 1 :(得分:1)
从我看到的情况来看,SPLIT_STR(l.en, ',', 1)
始终为null
(在table3.en
中没有任何内容可以拆分)另外,表table1.location = l.id
的连接条件对于您的数据始终为false (london
和england
都不等于london,england
)。
根据您发布的所需输出,我认为您正在寻找类似的东西(我不确定什么是language.url = 'europe-countries'
,我在问题中没有看到名为“language”的表或别名,所以我只是忽略了它)
SELECT t1.`type` AS `type`,
MAX(CASE WHEN t3.id = SPLIT_STR(t1.location, ',', 1) THEN t3.en END) as `city`,
MAX(CASE WHEN t3.id = SPLIT_STR(t1.location, ',', 2) THEN t3.en END) as `country`
FROM table1 t1
INNER JOIN table2 t2 ON (t2.id = t1.id)
LEFT JOIN table3 t3 ON
(t3.id = SPLIT_STR(t1.location, ',', 1) OR t3.id = SPLIT_STR(t1.location, ',', 2))
GROUP BY t1.`type`
已更新(l.en已被t1.location
替换)