Can we get records “Jone Deo” or “Deo Jone” with a single MySQL query?


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

mysql> create table DemoTable
   -> (
   -> ClientName varchar(100)
   -> );
Query OK, 0 rows affected (0.85 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John Smith');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Smith John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Jone Deo');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Deo Jone');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Chris Brown');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+
| ClientName  |
+-------------+
| John Smith  |
| Smith John  |
| Jone Deo    |
| Deo Jone    |
| Chris Brown |
+-------------+
5 rows in set (0.00 sec)

Following is the query to get records “Jone Deo” or “Deo Jone” in a single MySQL query −

mysql> select *from DemoTable
   -> where ClientName
   -> LIKE
   -> (SELECT SUBSTRING_INDEX("%Jone% %Deo%", " ", -1))
   -> or
   -> (SELECT SUBSTRING_INDEX("%Deo% %Jone%", " ", 1));

This will produce the following output −

+------------+
| ClientName |
+------------+
| Jone Deo   |
| Deo Jone   |
+------------+
2 rows in set (0.00 sec)
raja
Published on 12-Jul-2019 14:26:41
Advertisements