在本教程中,您将学习如何使用sql or
运算符组合两个布尔表达式。
sql or
是一个逻辑运算符,它组合两个布尔表达式。 sql or
运算符计算结果返回true
或false
,具体取决于表达式的结果。
or
运算符通常用于在select,update或delete语句的where子句中,以形成灵活的条件。
以下说明了sql or运算符的语法:
select
column1,
column2,
...
from
table1
where
expression1
or expression2;
下表显示了比较true
,false
和null
值时or
运算符的结果。
true | false | null | |
---|---|---|---|
true | true | true | true |
false | true | false | null |
null | true | null | null |
请注意,如果任一表达式为true
,则or
运算符始终返回true
。
如果数据库系统支持短路功能,则只要一个表达式为真,or
运算符就会停止评估条件的其余部分。
注意,短路功能可以帮助数据库系统通过在确定结果后立即中止处理逻辑表达式的剩余部分来节省cpu计算。 有关短路功能的更多信息,请查看sql and运算符教程。
将or
运算符与and
运算符一起使用时,数据库系统会在and
运算符之后计算or
运算符。 它叫作优先规则。 但是,可以使用括号更改评估顺序。
我们将使用示例数据库中的employees
表来演示or
运算符。
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
以下声明查找了1997
年或1998
年加入公司的所有员工。
select
first_name, last_name, hire_date
from
employees
where
year (hire_date) = 1997 or year (hire_date) = 1998
order by
first_name, last_name;
执行上面示例代码,得到以下结果 -
要查找1997
年或1998
年加入公司并在部门id为3
中工作的所有员工,可以使用and
和or
运算符,如下所示:
select
first_name, last_name, hire_date, department_id
from
employees
where
department_id = 3
and (
year (hire_date) = 1997
or year (hire_date) = 1998
)
order by
first_name, last_name;
执行上面查询语句,得到以下结果 -
如果不使用括号,查询将检索1997
年加入公司并在部门id为3
工作的员工或1998
年加入公司的员工(不限部门是哪个)。
这是因为数据库系统在and
运算符之后计算or
运算符。
select
first_name, last_name, hire_date, department_id
from
employees
where
department_id = 3
and year (hire_date) = 1997
or year (hire_date) = 1998
order by
first_name, last_name;
执行上面查询语句,得到以下结果 -
如果查询使用许多or
运算符,则将难以阅读。 要使查询更具可读性,可以使用in运算符。
例如,以下查询查找在1990
年或1999
年或2000
年加入公司的所有员工。
select
first_name,
last_name,
hire_date
from
employees
where
year (hire_date) = 2000
or year (hire_date) = 1999
or year (hire_date) = 1990;
可以通过in
运算符替换or
运算符,如下所示:
select
first_name,
last_name,
hire_date
from
employees
where
year (hire_date) in (1990, 1999, 2000)
order by
hire_date;
执行上面示例代码,得到以下结果 -
+------------+-----------+------------+
| first_name | last_name | hire_date |
+------------+-----------+------------+
| alexander | lee | 1990-01-03 |
| diana | chen | 1999-02-07 |
| kimberely | yang | 1999-05-24 |
| karen | zhang | 1999-08-10 |
| min | su | 1999-12-07 |
| charles | yang | 2000-01-04 |
+------------+-----------+------------+
6 rows in set
在本教程中,您已经学习了如何使用sql or
运算符组合两个布尔表达式以形成灵活的条件。