首先规格化字符串,删除空的位置,并确保最后有一个%:
select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1
然后我们可以用一个技巧来计算条目的数量。将'%'替换为'%',并计算添加到字符串的空格数。例如:
select length(replace(str, '%', '% ')) - length(str)
as LocationCount
from (
select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1
) normalized
使用SUBSTRING_INDEX,我们可以为多个位置添加列:
select length(replace(str, '%', '% ')) - length(str)
as LocationCount
, substring_index(substring_index(str,'%',1),'%',-1) as Loc1
, substring_index(substring_index(str,'%',2),'%',-1) as Loc2
, substring_index(substring_index(str,'%',3),'%',-1) as Loc3
from (
select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1
) normalized
对于示例US%UK%JAPAN%CANADA
,这个打印:
所以你看它可以做,但解析字符串不是SQL的优势之一。
感谢您的查询。但计数Numberoflocations只返回1时,表中的位置超过一个 – Paulraj 2009-11-04 12:29:38
对,我想我明白你的意思了。我会编辑答案。 – Andomar 2009-11-04 12:39:53