MySQL數據庫針對這一問題提供了一種基於內建的全文查找方式的解決方案。在此,開發者只需要簡單地標記出需要全文查找的字段,然後使用特殊的MySQL方法在那些字段運行搜索,這不僅僅提高了性能和效率因為MySQL數據庫對這些字段做了索引來優化搜索),而且實現了更高質量的搜索,因為MySQL使用自然語言來智能地對結果評級,以去掉不相關的項目。
此篇文章將向您講述在MySQL中如何進行全文搜索。
1、設置基本表格
從創建例子表格開始,使用以下的SQL命令
以下為引用的內容:
mysql> CREATE TABLE reviews (id INT(5)
PRIMARY KEY NOT NULL AUTO_INCREMENT, data TEXT);
以上命令創建了一個簡單的音樂專集資料庫主要是整段的文字),然後向這個表格中添加一些記錄:
以下為引用的內容:
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!');
驗證數據的正確錄入:
以下為引用的內容:
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、定義全文搜索字段
接下來,定義您要作為全文搜索索引的字段
以下為引用的內容:
mysql> ALTER TABLE reviews ADD FULLTEXT INDEX (data);
Query OK, 3 rows affected (0.21 sec)
Records: 3 Duplicates: 0 Warnings: 0
使用SHOW INDEXES命令來檢查索引已經被添加了:
以下為引用的內容:
mysql> SHOW INDEXES FROM reviews;
+---------+---------------+--------+------+------------+---------+
| Table | Column_name | Packed | Null | Index_type | Comment |
----------+---------------+--------+------+------------+---------+
| reviews | id | NULL | | BTREE | ||
reviews | data | NULL | YES | FULLTEXT | |
+---------+---------------+--------+------+------------+---------+
在MySQL數據庫中搜索功能是MySQL數據庫中比較重要的功能之一,使用全文搜索給數據庫管理帶來了很大的便利。