一、条件评估
1、 and 与 or 的使用
2、括号: 多于2个条件以上时,一定要使用圆括号。
有助于逻辑清晰与便与阅读。
3、not: not操作符,我们一般不使用。因为逻辑上的非我们一般可以通过改写条件而达到。
eg1:
select * from employee em
where (em.end_date is null or em.start_date < '2007-1-1')
and em.title like '%teller%'
eg2:
select * from employee em
where em.end_date is null or em.start_date < '2007-1-1' and em.title like '%teller%'
eg2中最后那个and em.title like '%teller%'实际是没有起作用。
二、 构建条件
where 子句的条件构建: 只能是针对表中的列字段。(对于聚合类型,我们用having 来构建。)
条件是由 单个或包含多个操作符 的表达式构成。表达式可以是以下一种:
1、数字
2、表或视图中的列
3、字符串,如‘Teller'
4、内建函数,比如函数contat('a','','b')
5、子查询
6、表达式列
7、比较操作符 如:= ,!= ,<,>,like , in , between
8、算术操作符,比如:+ , -, * , /
三、条件类型
1、相等条件: =
不等条件: != 或<>
eg:
select *
from product p
inner join product_type pt on pt.product_type_cd = p.product_type_cd
where pt.name <> 'Customer Accounts'
eg:
delete from account ac
where ac.status = 'CLOSE' and year(close_date) = 2002
2、范围条件: < , <= , > ,>= ,between
eg:
select em.*
from employee em
where em.start_date between '2003-01-01' and '2004-01-01'
一般情况我们可以用>= 与<= 代替between
3、成员条件: in , not in
select ac.*
from account ac
where ac.product_cd in (
select product_cd from product where product_type_cd = 'ACCOUNT'
)
4、 匹配条件: 内建函数(如left() ),使用通配符(正好一个字符 _ , 任意数目的字符 % ),正则表达式(regexp ' ')
eg:
select em.lname
from employee em
where lname like '_a%e%'
四、null值的处理: 表达式可以为null , 但是不能等于null
eg:
select em.emp_id , em.fname,em.lname,em.superior_emp_id
from employee em
where em.superior_emp_id is null
注意:有时的查询不能漏悼值为null的情况