怎樣在MySQL中獲得更好的搜索結(jié)果
MySQL數(shù)據(jù)庫針對這一問題提供了一種基于內(nèi)建的全文查找方式的解決方案。在此,開發(fā)者只需要簡單地標(biāo)記出需要全文查找的字段,然后使用特殊的MySQL方法在那些字段運行搜索,這不僅僅提高了性能和效率(因為MySQL數(shù)據(jù)庫對這些字段做了索引來優(yōu)化搜索),而且實現(xiàn)了更高質(zhì)量的搜索,因為MySQL使用自然語言來智能地對結(jié)果評級,以去掉不相關(guān)的項目。
此篇文章將向您講述在MySQL中如何進(jìn)行全文搜索。
1、設(shè)置基本表格
從創(chuàng)建例子表格開始,使用以下的SQL命令
以下為引用的內(nèi)容:
mysql> CREATE TABLE reviews (id INT(5)
PRIMARY KEY NOT NULL AUTO_INCREMENT, data TEXT);
以上命令創(chuàng)建了一個簡單的音樂專集資料庫(主要是整段的文字),然后向這個表格中添加一些記錄:
以下為引用的內(nèi)容:
mysql> INSERT INTO `reviews` (`id`, `data`) VALUES
(1, 'Gingerboy has a new single out called Throwing Rocks.
It\'s great!');mysql> INSERT INTO `reviews` (`id`, `data`)
VALUES (2, 'Hello all, I really like the new Madonna single.
One of the hottest tracks currently playing...
I\'ve been listening to it all day');mysql> INSERT INTO `reviews`
(`id`, `data`)VALUES (3, 'Have you heard the new band Hotter
Than Hell?They have five members and they burn their
instruments when they play in concerts.
These guys totally rock! Like, awesome, dude!');
驗證數(shù)據(jù)的正確錄入:
以下為引用的內(nèi)容:
mysql> SELECT * FROM reviews;
+----+--------------------------------------------+
| id | data |
+----+--------------------------------------------+
| 1 | Gingerboy has a new single out called ... |
| 2 | Hello all, I really like the new Madon ... |
| 3 | Have you heard the new band Hotter Than... |
3 rows in set (0.00 sec)
2、定義全文搜索字段
接下來,定義您要作為全文搜索索引的字段
以下為引用的內(nèi)容:
mysql> ALTER TABLE reviews ADD FULLTEXT INDEX (data);
Query OK, 3 rows affected (0.21 sec)
Records: 3 Duplicates: 0 Warnings: 0
使用SHOW INDEXES命令來檢查索引已經(jīng)被添加了:
以下為引用的內(nèi)容:
mysql> SHOW INDEXES FROM reviews;
+---------+---------------+--------+------+------------+---------+
| Table | Column_name | Packed | Null | Index_type | Comment |
----------+---------------+--------+------+------------+---------+
| reviews | id | NULL | | BTREE | ||
reviews | data | NULL | YES | FULLTEXT | |
+---------+---------------+--------+------+------------+---------+
在MySQL數(shù)據(jù)庫中搜索功能是MySQL數(shù)據(jù)庫中比較重要的功能之一,使用全文搜索給數(shù)據(jù)庫管理帶來了很大的便利。
【編輯推薦】