我有一个这样的表:
id path
1 /
2 /city/
3 /city/europe/
4 /city/north america/
6 /city/europe/germany/berlin/
7 /city/europe/germany/
8 /city/north america/usa/
[...]
和这样的搜索字符串:
"/city/north america/usa/florida/miami/"
我需要选择搜索字符串中最长的路径,这样结果就是
id path
8 /city/north america/usa/
表中任何路径的每个父项都存在。路径可以任意长。搜索字符串至少包含“/”。
我可以想到一些解决方案,例如在列上使用通配符、拆分搜索字符串以及使用 IN 或连接执行选择。
最好和最快的方法是什么?
表格可以任意修改。
编辑:
迄今为止我提出的最快的解决方案:
SELECT * FROM table_name
WHERE path IN ('/','/city/','/city/north america/', '/city/north america/usa/', '/city/north america/usa/florida/', '/city/north america/usa/florida/miami/')
ORDER by LENGTH(path) DESC LIMIT 1;
最佳答案
SELECT *
FROM table_name
WHERE path REGEXP '^/city((((/north america)?/usa)?/florida)?/miami)?\/?$'
ORDER BY LENGTH(path) DESC
LIMIT 1
关于MySQL:选择搜索字符串中出现的最长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38942806/