PHP / MySQL搜索以满足错过的连字符

时间:2013-10-24 19:58:38

标签: php mysql search

我在PHP(Codeigniter)中有一个非常简单的搜索功能,它接受查询并尝试将其与MySQL表中的名称进行匹配。该表将名称拆分为别名,名字和姓氏:

$this->db->where("alias LIKE '%$query%' OR firstname LIKE '%$query%' OR lastname LIKE '%$query%' OR CONCAT(firstname,' ',lastname) LIKE '%$query%'");

这适用于大多数情况。问题出现在数据库中的一个名称 - 姓氏为Smith-Ponsonby(为了参数)。如果用户搜索Smith-Ponsonby,则会显示正确的结果。但是如果用户意外错过连字符并搜索Smith Ponsonby,则不会返回任何内容(正如我的代码所预期的那样)。但我想照顾这些意外情况。我需要一些非常简单的东西,但我的搜索只发现了非常精细的模糊搜索算法。任何想法都非常赞赏。

1 个答案:

答案 0 :(得分:2)

您可以为文本字段添加全文索引,例如:

create table people (
    id int unsigned auto_increment not null primary key,
    name varchar(255),
    fulltext(name)
);

插入一些测试值:

insert into people (name) values ('smith'),('smithers'),('wosmithling'),('smith-ponsonby');

然后使用MATCH()运算符进行查询,例如,仅针对'smith':

select * from people where match(name) against ('smith' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+

用短划线:

select * from people where match (name) against ('smith-ponsonby' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+

有一个空格:

select * from people where match (name) against ('smith ponsonby' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+