A single MySQL query to search multiple words from different column values

MySQLMySQLi Database

For this, you can use WHERE clause with multiple LIKE. Let us first create a table −

mysql> create table DemoTable1536
   -> (
   -> Sentence text
   -> );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1536 values('I like MySQL database.');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1536 values('Java is an Object Oriented Programming Language');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable1536 values('I only like data structure');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1536 values('MongoDB is NoSQL database');
Query OK, 1 row affected (0.46 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1536;

This will produce the following output −

+--------------------------------------------------+
| Sentence                                         |
+--------------------------------------------------+
| I like MySQL database.                           |
| Java is an Object Oriented Programming Language  |
| I only like data structure                       |
| MongoDB is NoSQL database                        |
+--------------------------------------------------+
4 rows in set (0.00 sec)

Following is the query to search multiple words −

mysql> select * from DemoTable1536
   -> where ( Sentence like '%like%') or (Sentence like '%database%') or (Sentence like '%data%');

This will produce the following output −

+----------------------------+
| Sentence                   |
+----------------------------+
| I like MySQL database.     |
| I only like data structure |
| MongoDB is NoSQL database  |
+----------------------------+
3 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 10:14:02
Advertisements