是否可以使用 soundex 将列的一部分与搜索词进行比较?例如,如果用户搜索“fiftythree”——它将找到“Nirve Sports Fifty-Three Cruiser in Gold Metallic”。我尝试将 soundex 与 locate 函数结合使用,但出现错误。这是我的 PHP 代码:
$soundex = soundex($keyword);
$soundexPrefix = substr($soundex, 0, 2);
$sql = "SELECT name ".
"FROM products WHERE SOUNDEX(LOCATE('$keyword', name)) LIKE '%$soundexPrefix%'";
最佳答案
您需要分解每个单词并进行 SOUNDEX
比较,这正是我要介绍的这个函数的作用。
使用函数
用法示例:SELECT p.name FROM products p WHERE soundex_match('fiftythree', p.name, ' ')
它需要 3 个参数:
- needle:你要找的词
- haysack:你正在搜索的单词串
- splitChar:将字符串拆分成的空白字符 单字。一般是空格(‘ ‘)
如果 haystack 中的任何单词听起来与 needle 相似,则该函数将返回 1,否则返回 0。
在您的数据库中创建函数
因此进入您的数据库(phpMyAdmin 或命令行)并执行此操作,您只需执行一次:
drop function if exists soundex_match;
delimiter $$
create function soundex_match (needle varchar(128), haystack text, splitChar varchar(1)) returns tinyint
deterministic
begin
declare spacePos int;
declare searchLen int default length(haystack);
declare curWord varchar(128) default '';
declare tempStr text default haystack;
declare tmp text default '';
declare soundx1 varchar(64) default soundex(needle);
declare soundx2 varchar(64) default '';
set spacePos = locate(splitChar, tempStr);
while searchLen > 0 do
if spacePos = 0 then
set tmp = tempStr;
select soundex(tmp) into soundx2;
if soundx1 = soundx2 then
return 1;
else
return 0;
end if;
end if;
if spacePos != 0 then
set tmp = substr(tempStr, 1, spacePos-1);
set soundx2 = soundex(tmp);
if soundx1 = soundx2 then
return 1;
end if;
set tempStr = substr(tempStr, spacePos+1);
set searchLen = length(tempStr);
end if;
set spacePos = locate(splitChar, tempStr);
end while;
return 0;
end
$$
delimiter ;
http://www.imranulhoque.com/mysql/mysql-function-soundex-match-multi-word-string/
关于php - soundex 可以用于 mysql 中列的一部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952959/