首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP / MySQL搜索以满足缺少连字符的需要

问PHP / MySQL搜索以满足缺少连字符的需要
EN

Stack Overflow用户
提问于 2013-10-25 03:58:38
回答 1查看 92关注 0票数 1

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

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

EN

回答 1

Stack Overflow用户

发布于 2013-10-25 04:14:24

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

代码语言:javascript
复制
create table people (
    id int unsigned auto_increment not null primary key,
    name varchar(255),
    fulltext(name)
);

插入一些测试值:

代码语言:javascript
复制
insert into people (name) values ('smith'),('smithers'),('wosmithling'),('smith-ponsonby');

然后使用MATCH()操作符进行查询,例如,仅查询'smith':

代码语言:javascript
复制
select * from people where match(name) against ('smith' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+

用破折号:

代码语言:javascript
复制
select * from people where match (name) against ('smith-ponsonby' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+

带空格:

代码语言:javascript
复制
select * from people where match (name) against ('smith ponsonby' in boolean mode);
+----+----------------+
| id | name           |
+----+----------------+
|  1 | smith          |
|  4 | smith-ponsonby |
+----+----------------+
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19575424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档