我在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,则不会返回任何内容(正如我的代码所期望的那样)。但我想要迎合这些意外的情况。我需要一些非常简单的东西,但我的搜索只找到了相当复杂的模糊搜索算法。任何想法都非常感谢。
发布于 2013-10-25 04:14:24
您可以向文本字段添加全文索引,例如:
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 |
+----+----------------+https://stackoverflow.com/questions/19575424
复制相似问题