Searching multiple columns for a row match in MySQL

MySQLMySQLi Database

For this, use UNION. Let us first create a table −

mysql> create table DemoTable645 (Id int,FirstName varchar(100));
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable645 values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable645 values(101,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable645 values(101,'Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable645 values(102,'Carol');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable645 values(100,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable645 values(100,'Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable645 values(101,'Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable645 values(101,'John');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable645;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  100 | Chris     |
|  101 | Robert    |
|  101 | Bob       |
|  102 | Carol     |
|  100 | John      |
|  100 | Robert    |
|  101 | Mike      |
|  101 | John      |
+------+-----------+
8 rows in set (0.00 sec)

Following is the query to search multiple columns −

mysql> select Id AS Records from DemoTable645 where Id LIKE '%100%'
   union
   select FirstName from DemoTable645 where FirstName LIKE '%John%'
   order by 1 LIMIT 3;

This will produce the following output −

+---------+
| Records |
+---------+
| 100     |
| John    |
+---------+
2 rows in set (0.00 sec)
raja
Published on 23-Aug-2019 11:08:01
Advertisements