MySQL检索行时AND和OR运算符的区别是什么?

MySQL检索行时AND和OR运算符的区别是什么?

AND和OR的区别在于,AND评估必须对两个条件都为true才能使整个条件为true。OR评估只要有一个条件为true就可以使整个条件为true。

让我们创建一个表 –

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)

使用insert命令向表中插入一些记录 –

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,则条件将为true。如果任何行的年龄为22,则它将为true。

现在让我们看看AND操作符的结果。

查询如下 –

mysql> select *from demo70
−> where name="John" and age=22;

这将产生以下输出 –

Empty set (0.00 sec)

AND操作符给出空集,因为没有任何一行具有相同的名称John和年龄22。

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程