如何使用 MySQL LIKE 获取具有多个值的字段?

mysqlmysqli database

要获取具有多个值的字段,请在 MySQL 中使用 LIKE 和 OR −

select *from yourTableName where yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ ……...N;

您可以借助表格 − 来理解

mysql> create table LikeDemo
   −> (
      −> Hobby varchar(200)
   −> );
Query OK, 0 rows affected (1.71 sec)

使用 insert 命令在表中插入一些记录。在表中插入记录的查询如下 −

mysql> insert into LikeDemo values('Reading Book');
Query OK, 1 row affected (0.13 sec)

mysql> insert into LikeDemo values('Playing Cricket Match');
Query OK, 1 row affected (0.16 sec)

mysql> insert into LikeDemo values('Playing Hockey Match');
Query OK, 1 row affected (0.27 sec)

mysql> insert into LikeDemo values('Reading Novel');
Query OK, 1 row affected (0.14 sec)

mysql> insert into LikeDemo values('Swimming');
Query OK, 1 row affected (0.10 sec)

Displaying all records with the help of select statement. The query is as follows:

mysql> select *from LikeDemo;

以下是输出 −

+-----------------------+
| Hobby                 |
+-----------------------+
| Reading Book          |
| Playing Cricket Match |
| Playing Hockey Match  |
| Reading Novel         |
| Swimming              |
+-----------------------+
5 rows in set (0.00 sec)

使用 LIKE 获取具有多个值的字段的查询如下 −

mysql> select *from LikeDemo where Hobby like '%Cricket%' or Hobby like '%Reading%';

以下是输出 −

+-----------------------+
| Hobby                 |
+-----------------------+
| Reading Book          |
| Playing Cricket Match |
| Reading Novel         |
+-----------------------+
3 rows in set (0.00 sec)

相关文章