Query for implementing MySQL LIKE as MySQL IN?


To implement a query like MySQL IN(), you need to use COUNT(), IF() along with LIKE operator. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Subject varchar(80)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('MySQLMongoDB');
Query OK, 1 row affected (0.86 sec)
mysql> insert into DemoTable values('MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('JavaMySQL');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Java');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| Subject      |
+--------------+
| MySQLMongoDB |
| MySQL        |
| JavaMySQL    |
| MongoDB      |
| Java         |
+--------------+
5 rows in set (0.00 sec)

Here is the query for implementing LIKE as IN() −

mysql> select
   -> count(if(Subject like '%MySQL%',1,NULL)) as MySQLCount,
   -> count(if(Subject like '%Java%',1,NULL)) as JavaCount,
   -> count(if(Subject like '%MongoDB%',1,NULL)) as MongoDBCount
   -> from DemoTable;

This will produce the following output −

+------------+-----------+--------------+
| MySQLCount | JavaCount | MongoDBCount |
+------------+-----------+--------------+
|          3 |         2 |            2 |
+------------+-----------+--------------+
1 row in set (0.00 sec)

Updated on: 17-Dec-2019

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements