where语句
select * from `employee`
where end_date is null and
(title='Teller' or start_date <'2007-1-1');
where 语句中第一个条件为True,圆括号中两个条件满足一个,就可以被选中。
设计到关系运算,与或非的否定语句
select * from `employee`
where end_date is null
and not (title='Teller' or start_date <'2007-1-1');
not 关键字 (a or b),实际条件 是 非a且非b。
因为not 关键字增加了 条件评估的困难,一般很少用,以上语句可以写成如下
select * from `employee`
where end_date is null
and (title != 'Teller' and start_date >='2007-1-1');
!= 不等于,此外OR 被AND 取代,因为上个语句not 关键字筛选的条件是非a且非b。
将一个表达式等于另一个表达式。
例子:
title =‘Teller’
dept_id = (select dept_id from `department` where name='Loans')
select * from `employee` where dept_id = (select dept_id from `department` where name='Loans');
select pt.name as product_type,p.name as
product from `product` as p inner join `product_type` as pt on p.product_type_cd=pt.product_type_cd
where pt.name ='Customer Accounts';
构造不等式 != 或者 <>
select pt.name as product_type, p.name as product
from `product_type` as pt inner join `product` as p on pt.product_type_cd=p.product_type_cd
where pt.name <> 'Customer Accounts';
坑:我们查询的子句,多个列用逗号,隔开
删除账户为非活跃状态,且已经销户。
delete from `account` where status='CLOSED' and year(closed_date)=2002;
坑:删除delete 直接from 表名 , 不需要delect * from 表名。
构建条件检查表达式是否处于某个区间。
select emp_id,fname,lname,start_date from `employee`
where start_date <'2007-1-1';
一种方法是
select emp_id ,fname,lname,start_date from `employee`
where start_date >='2005-1-1' and start_date <'2007-1-1';
另一种方法,使用between 关键字,使用关键字,and 前应该,小于,and后。
且上下限范围是闭合的,也就是>= <=。
select emp_id,fname,lname,start_date from `employee`
where start_date between '2005-1-1' and '2007-1-1';
查询500-00-0000 到999-99-9999之间范围
select cust_id,fed_id from `customer`
where cust_type_cd='I' and fed_id between '500-00-0000' and '999-99-9999';
select account_id,product_cd,cust_id,avail_balance from `account`
where product_cd in ('CHK','SAV','CD','MM');
select account_id,product_cd,cust_id,avail_balance from `account`
where product_cd in (select product_cd from `product` where product_type_cd='Account');
否定,不在某个集合范围内。
select account_id,product_cd,cust_id,avail_balance from `account`
where product_cd not in ('CHK','SAV','CD','MM');
a、使用内置函数
查询以T开头的lname
select * from `employee`
where left(lname,1)='T';
可以构建搜索表达式定位这些字符串,配合like操作符。
‘_' 匹配一个字符;
'%'匹配任意数目的字符,范围【0,+---】,包含0个。
select * from `employee`
where lname like '_a%e%';
查找这个格式的相匹配的500-9999-00
select * from `customer`
where fed_id like '___-____-__';
操作符:regexp
select * from `employee`
where lname regexp '^[FG]';
null表示缺失值
适用的场景:
注意点:
select * from `employee`
where superior_emp_id is null;
以上语句,将返回superior_emp_id 是空值的行;
如果这样是= null,则不会返回值。
select * from `employee`
where superior_emp_id = null;
select * from `employee`
where superior_emp_id is not null;
一般会犯这个错误。
select * from `employee`
where superior_emp_id !=6;
观察结果,会发现有个雇员没有列出了,因为其superior_emp_id的值是null。
select * from `employee`
where superior_emp_id !=6 or superior_emp_id is null;