今天在写这个网站的全文搜索的时候遇到了一些问题,开始的时候我是这样写的SELECT * FROM `article` WHERE ti like '%a%' or con like '%a%' 这样是可以的,后来一个哥们告诉我这样多个like的话会出对服务器和数据库的压力比较大的,建议我用全文搜索吧。找了半天,找到这个文章,还不错的吧。 对于全站搜索,或者是一些大容量的搜索很有用的。ok,认真看吧。

到 3.23.23 时,mysql 开始支持全文索引和搜索。全文索引在 mysql 中是一个 fulltext 类型索引。fulltext 索引用于 myisam 表,可以在 create table 时或之后使用 alter tablecreate indexcharvarchartext 列上创建。对于大的数据库,将数据装载到一个没有 fulltext 索引的表中,然后再使用 alter table (或 create index) 创建索引,这将是非常快的。将数据装载到一个已经有 fulltext 索引的表中,将是非常慢的。

全文搜索通过 match() 函数完成。

mysql> create table articles (

-> id int unsigned auto_increment not null primary key,

-> title varchar(200),

-> body text,

-> fulltext (title,body)

-> );

query ok, 0 rows affected (0.00 sec)

mysql> insert into articles values

-> (null,'mysql tutorial', 'dbms stands for database ...'),

-> (null,'how to use mysql efficiently',
'after you went through a ...'),

-> (null,'optimising mysql',
'in this tutorial we will show ...'),


-> (null,'1001 mysql tricks','1.
never run mysqld as root. 2. ...'),

-> (null,'mysql vs. yoursql',
'in the following database comparison ...'),

-> (null,'mysql security',
'when configured properly, mysql ...');
query ok, 6 rows affected (0.00 sec)
records: 6 duplicates: 0 warnings: 0
mysql> select * from articles
-> where match (title,body) against ('database');
+----+-------------------+------------------------------------------+
| id | title | body |
+----+-------------------+------------------------------------------+
| 5 | mysql vs. yoursql | in the following database comparison ... |
| 1 | mysql tutorial | dbms stands for database ... |
+----+-------------------+------------------------------------------+
2 rows in set (0.00 sec)

函数 match() 对照一个文本集(包含在一个 fulltext 索引中的一个或多个列的列集)执行一个自然语言搜索一个字符串。搜索字符串做为 against() 的参数被给定。搜索以忽略字母大小写的方式执行。对于表中的每个记录行,match() 返回一个相关性值。即,在搜索字符串与记录行在 match() 列表中指定的列的文本之间的相似性尺度。

match() 被使用在一个 where 子句中时 (参看上面的例子),返回的记录行被自动地以相关性从高到底的次序排序。相关性值是非负的浮点数字。零相关性意味着不相似。相关性的计算是基于:词在记录行中的数目、在行中唯一词的数目、在集中词的全部数目和包含一个特殊词的文档(记录行)的数目。

它也可以执行一个逻辑模式的搜索。这在下面的章节中被描述。

前面的例子是函数 match() 使用上的一些基本说明。记录行以相似性递减的顺序返回。