1

我在 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,则不会返回任何内容(正如我的代码所预期的那样)。但我想迎合这些意外情况。我需要一些非常简单的东西,但我的搜索只发现了相当复杂的模糊搜索算法。任何想法都非常感谢。

4

1 回答 1

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 |
+----+----------------+
于 2013-10-24T20:14:24.280 回答