在 MySQL 中 AND、OR 操作符在检索行时有什么区别?
AND 和 OR 的区别在于 AND 要求两个条件都为真,则总体条件才为真。OR 要求一个条件为真,则总体条件才为真。
让我们创建一个表 -
mysql> create table demo70 −> ( −> id int not null auto_increment primary key, −> name varchar(20), −> age int −> ); Query OK, 0 rows affected (0.67 sec)
使用插入命令,插入一些记录到表中 -
mysql> insert into demo70(name,age) values('John',23);
Query OK, 1 row affected (0.18 sec)
mysql> insert into demo70(name,age) values('David',21);
Query OK, 1 row affected (0.08 sec)
mysql> insert into demo70(name,age) values('Mike',22);
Query OK, 1 row affected (0.15 sec)
mysql> insert into demo70(name,age) values('Chris',20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into demo70(name,age) values('John',24);
Query OK, 1 row affected (0.13 sec)
mysql> insert into demo70(name,age) values('David',22);
Query OK, 1 row affected (0.15 sec)使用 select 语句在表中显示记录 -
mysql> select *from demo70;
这将产生以下输出 -
+----+-------+------+ | id | name | age | +----+-------+------+ | 1 | John | 23 | | 2 | David | 21 | | 3 | Mike | 22 | | 4 | Chris | 20 | | 5 | John | 24 | | 6 | David | 22 | +----+-------+------+ 6 rows in set (0.00 sec)
OR 运算符查询如下 -
mysql> select *from demo70 −> where name="John" or age=22;
这将产生以下输出 -
+----+-------+------+ | id | name | age | +----+-------+------+ | 1 | John | 23 | | 3 | Mike | 22 | | 5 | John | 24 | | 6 | David | 22 | +----+-------+------+ 4 rows in set (0.00 sec)
在 OR 结果中,如果 name 是 John,则条件为真。如果任何一行 age 为 22,则为真。
现在让我们看看 AND 运算符的结果。
查询如下 -
mysql> select *from demo70 −> where name="John" and age=22;
这将产生以下输出 -
Empty set (0.00 sec)
AND 返回空集,因为没有一行具有相同的 name John 和 age 22。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP