全文索引的创建
当对文章字段或有大量文字的字段进行检索时,会使用到全文索引。
MySQL提供全文索引机制,但是有要求,要求表的存储引擎必须是MyISAM,而且默认的全文索引支持英文,不支持中文。
(为啥一定要用MyISAM呢? -- 因为InnoDB不支持全文索引)
如果对中文进行全文检索,可以使用sphinx的中文版(coreseek)。
CREATE TABLE articles (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(200),
body TEXT,
FULLTEXT (title,body)
)engine=MyISAM;
INSERT INTO articles (title,body) VALUES
('MySQL Tutorial','DBMS stands for DataBase ...'),
('How To Use MySQL Well','After you went through a ...'),
('Optimizing MySQL','In this tutorial we will show ...'),
('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
('MySQL vs. YourSQL','In the following database comparison ...'),
('MySQL Security','When configured properly, MySQL ...');
这里的省略号表示的都是大文本的意思
查询有没有database数据
如果使用如下查询方式,虽然查询出数据,但是没有使用到全文索引
mysql> select * from articles where body like '%database%';
+----+-------------------+------------------------------------------+
| id | title | body |
+----+-------------------+------------------------------------------+
| 1 | MySQL Tutorial | DBMS stands for DataBase ... |
| 5 | MySQL vs. YourSQL | In the following database comparison ... |
+----+-------------------+------------------------------------------+
可以用explain工具看一下,是否使用到索引
mysql> explain select * from articles where body like '%database%'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: articles
type: ALL
possible_keys: NULL
key: NULL <== key为null表示没有用到索引
key_len: NULL
ref: NULL
rows: 6
Extra: Using where
1 row in set (0.00 sec)
如何使用全文索引呢?
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 ... |
+----+-------------------+------------------------------------------+
通过explain来分析这个sql语句
mysql> explain SELECT * FROM articles WHERE MATCH (title,body) AGAINST
('database')\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: articles
type: fulltext
possible_keys: title
key: title <= key用到了title
key_len: 0
ref:
rows: 1
Extra: Using where
查询索引
- 第一种方法: show keys from 表名
第二种方法: show index from 表名;mysql> show keys from goods\G *********** 1. row *********** Table: goods <= 表名 Non_unique: 0 <= 0表示唯一索引 Key_name: PRIMARY <= 主键索引 Seq_in_index: 1 Column_name: goods_id <= 索引在哪列 Collation: A Cardinality: 0 Sub_part: NULL Packed: NULL Null: Index_type: BTREE <= 以二叉树形式的索引 Comment: 1 row in set (0.00 sec)
第三种方法(信息比较简略): desc 表名;
struct page
{
struct page *next;
string page *prev;
char buffer[NUM];
};---16KB , new page,