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)
阅读更多:MySQL 教程
极客教程