如何对两个 MySQL LIKE 语句进行 OR 运算?
mysqlmysqli database
您可以使用以下语法对两个 like 语句进行 OR 运算 −
SELECT *FROM yourTableName WHERE (yourColumnName like '%yourValue1%' OR yourColumnNamelike '%yourValue2%') AND yourColumnName = yourValue;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table ORLikeDemo -> ( -> Id int not null auto_increment, -> FirstName varchar(15), -> LastName varchar(15), -> Primary Key(Id) -> ); Query OK, 0 rows affected (1.19 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into ORLikeDemo(FirstName,LastName) values('John','Smith'); Query OK, 1 row affected (0.13 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('Carol','Taylor'); Query OK, 1 row affected (0.23 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('John','Doe'); Query OK, 1 row affected (0.11 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('Bob','Jones'); Query OK, 1 row affected (0.20 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('David','Miller'); Query OK, 1 row affected (0.17 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('Mike','Williams'); Query OK, 1 row affected (0.11 sec) mysql> insert into ORLikeDemo(FirstName,LastName) values('Sam','Taylor'); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from ORLikeDemo;
以下是输出 −
+----+-----------+----------+ | Id | FirstName | LastName | +----+-----------+----------+ | 1 | John | Smith | | 2 | Carol | Taylor | | 3 | John | Doe | | 4 | Bob | Jones | | 5 | David | Miller | | 6 | Mike | Williams | | 7 | Sam | Taylor | +----+-----------+----------+ 7 rows in set (0.00 sec)
这是使用两个 LIKE 和 OR 运算符的查询 −
mysql> select *from ORLikeDemo where (LastName like '%Smith%' OR LastName like'%Doe%') AND Id = 3;
以下是输出 −
+----+-----------+----------+ | Id | FirstName | LastName | +----+-----------+----------+ | 3 | John | Doe | +----+-----------+----------+ 1 row in set (0.03 sec)