本教程将介绍sql and运算符,并演示如何将其应用于在sql语句的where子句中形成条件。
and运算符是一个逻辑运算符,它在select,update或delete语句的where子句中组合了两个布尔表达式。 以下说明了and运算符的语法:
expression1 and expression2;
如果两个表达式的计算结果为true,则and运算符返回true。 如果两个表达式中的一个为false,即使其中一个表达式为null,则and运算符返回false。
下表说明了比较true,false和null值时and运算符的结果:
| - | true | false | null |
|---|---|---|---|
| true | true | false | null |
| false | false | false | false |
| null | null | false | null |
我们将使用示例数据库中的employees表来演示sql and运算符。
mysql> desc employees;
+---------------+--------------+------+-----+---------+----------------+
| field | type | null | key | default | extra |
+---------------+--------------+------+-----+---------+----------------+
| employee_id | int(11) | no | pri | null | auto_increment |
| first_name | varchar(20) | yes | | null | |
| last_name | varchar(25) | no | | null | |
| email | varchar(100) | no | | null | |
| phone_number | varchar(20) | yes | | null | |
| hire_date | date | no | | null | |
| job_id | int(11) | no | mul | null | |
| salary | decimal(8,2) | no | | null | |
| manager_id | int(11) | yes | mul | null | |
| department_id | int(11) | yes | mul | null | |
+---------------+--------------+------+-----+---------+----------------+
10 rows in set
以下语句查找同时具有工作id是9和薪水大于5000的所有员工:
select
first_name, last_name, job_id, salary
from
employees
where
job_id = 9
and salary > 5000;
执行上面查询语句,得到以下结果 -
+------------+-----------+--------+--------+
| first_name | last_name | job_id | salary |
+------------+-----------+--------+--------+
| alexander | lee | 9 | 9000 |
| bruce | wong | 9 | 6000 |
+------------+-----------+--------+--------+
2 rows in set
要查找1997年到1998年之间加入公司的所有员工,使用and运算符,如下所示:
select
first_name, last_name, hire_date
from
employees
where
year (hire_date) >=1997
and year (hire_date) <= 1998;
执行上面示例代码,得到以下结果 -
短路功能允许数据库系统在确定结果后立即停止评估逻辑表达式的其余部分。
让我们看一个例子来更好地理解短路计算功能的工作原理。
请参阅以下条件:
1 = 0 and 1 = 1;
数据库系统首先处理两个比较,并使用and运算符来评估两个结果。
但是,使用短路评估功能,数据库系统只需要评估表达式的左侧部分,因为左侧部分(1 = 0)返回false,导致整个条件返回false,而不管右侧部分条件的结果如何。
因此,短路功能可以减少cpu计算时间,并且在某些情况下有助于防止运行时错误。 考虑以下情况:
1 = 0 and 1/0;
如果数据库系统支持短路功能,则不会评估导致除零错误的表达式(1/0)的右侧部分。
现在,您应该了解sql and运算符的工作原理以及如何应用它以在查询中形成复杂查询条件。