如何實現 MySQL中的關鍵字搜尋?
要實現 MySQL 中的關鍵字搜尋,可以使用 LIKE 運算子。其語法如下所述 −
SELECT *FROM yourTableName where yourColumnName Like ‘%anyKeywordName%’ or yourColumnName Like ‘%anyKeywordName%’;
為了進一步瞭解它,我們首先建立一個表。以下是建立表的查詢 −
mysql> create table KeywordSearchDemo −> ( −> StudentId int −> , −> StudentName varchar(100) −> ); Query OK, 0 rows affected (0.86 sec)
使用 INSERT 命令在表中插入一些記錄。插入記錄的查詢如下所示 −
mysql> insert into KeywordSearchDemo values(100,'Adam John'); Query OK, 1 row affected (0.40 sec) mysql> insert into KeywordSearchDemo values(101,'John Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into KeywordSearchDemo values(103,'John Taylor'); Query OK, 1 row affected (0.15 sec) mysql> insert into KeywordSearchDemo values(104,'Carol Taylor'); Query OK, 1 row affected (0.21 sec) mysql> insert into KeywordSearchDemo values(105,'Maria Garcia'); Query OK, 1 row affected (0.20 sec) mysql> insert into KeywordSearchDemo values(106,'James Smith'); Query OK, 1 row affected (0.12 sec) mysql> insert into KeywordSearchDemo values(110,'Mike Brown'); Query OK, 1 row affected (0.22 sec)
使用 select 語句顯示錶中的所有記錄。查詢如下所示 −
mysql> select *from KeywordSearchDemo;
以下為輸出 −
+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 100 | Adam John | | 101 | John Smith | | 103 | John Taylor | | 104 | Carol Taylor | | 105 | Maria Garcia | | 106 | James Smith | | 110 | Mike Brown | +-----------+--------------+ 7 rows in set (0.00 sec)
以下查詢僅選擇與關鍵字相關的那些名稱。查詢如下所示 −
mysql> select StudentName from KeywordSearchDemo −> where StudentName Like '%John%' or StudentName Like '%Taylor%';
以下為顯示帶有關鍵字“John”和“Taylor”的記錄的輸出 −
+--------------+ | StudentName | +--------------+ | Adam John | | John Smith | | John Taylor | | Carol Taylor | +--------------+ 4 rows in set (0.10 sec)
您甚至可以從表中返回 StudentId 列。
mysql> select *from KeywordSearchDemo −> where StudentName Like '%John%' or StudentName Like '%Taylor%';
以下為輸出 −
+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 100 | Adam John | | 101 | John Smith | | 103 | John Taylor | | 104 | Carol Taylor | +-----------+--------------+ 4 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP