将 MySQL LIKE 实现为 MySQL IN 的查询?

mysqlmysqli database

要实现类似 MySQL IN() 的查询,您需要使用 COUNT()、IF() 以及 LIKE 运算符。让我们首先创建一个表 −

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

使用 insert 命令在表中插入一些记录 −

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)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

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

以下是将 LIKE 实现为 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;

这将产生以下输出 −

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

相关文章