where 子句中标准形式的定义
三个布尔连接符(and、or 和 not)的使用是受到严格控制的:
- not 只适用于简单条件。不能将它应用于包含and 或者 or 的复合条件中。
- and 只用于组合简单条件以及包括 not 的条件。 这些条件都不允许包含 or 。 多个条件可以使用 and 组合在一起。 如果使用一个以上的 and 条件,这些条件可以以任意顺序组合起来,并且不需要括号。通常每个复合条件都是包在括号中。
- or是顶级连接符。它可以组合那些使用 and 和 not 的所有复合条件。 如果有一个以上的or, 这些复合条件可以以任何顺序组合起来, 并且不需要括号。
将如下 where 子句写成标准形式:
select *
from 1_employees
where not ((first_name = 'JIM' or first_name = 'DAN')
and (last_name = 'BROWN' or last_name = 'SMITH'));
漏掉圆括号—— 一个常见错误
select *
from 1_employees
where employee_id = 203
or employee_id = 204
or employee_id = 205
and dept_code = 'SAL';
人们通常期待的
select *
from 1_employees
where (employee_id = 203
or employee_id = 204
or employee_id = 205 )
and dept_code = 'SAL';
计算机是理解
select *
from 1_employees
where (employee_id = 203)
or ( employee_id = 204)
or ( employee_id = 205 )
and dept_code = 'SAL');