How to implement a Keyword Search in MySQL?

MySQLMySQLi Database

To implement a keyword search in MySQL, you can use LIKE operator. The syntax is as follows −

SELECT *FROM yourTableName
where yourColumnName Like ‘%anyKeywordName%’
or yourColumnName Like ‘%anyKeywordName%’;

To understand it further, let us first create a table. The following is the query to create a table −

mysql> create table KeywordSearchDemo
   −> (
   −> StudentId int
   −> ,
   −> StudentName varchar(100)
   −> );
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using INSERT command. The query to insert record is as follows −

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)

Display all records from the table using select statement. The query is as follows −

mysql> select *from KeywordSearchDemo;

The following is the output −

+-----------+--------------+
| 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)

Here is the query that selects only those names which are related to a keyword. The query is as follows −

mysql> select StudentName from KeywordSearchDemo
   −> where StudentName Like '%John%' or StudentName Like '%Taylor%';

The following is the output that displays records with the keywords “John” and “Taylor” −

+--------------+
| StudentName  |
+--------------+
| Adam John    |
| John Smith   |
| John Taylor  |
| Carol Taylor |
+--------------+
4 rows in set (0.10 sec)

You can return even StudentId column from table.

mysql> select *from KeywordSearchDemo
   −> where StudentName Like '%John%' or StudentName Like '%Taylor%';

The following is the output −

+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
|       100 | Adam John    |
|       101 | John Smith   |
|       103 | John Taylor  |
|       104 | Carol Taylor |
+-----------+--------------+
4 rows in set (0.00 sec)
raja
Published on 16-Jan-2019 10:33:12
Advertisements