where子句
比较运算符: < , <= , > , >= , = , != , !< , !> . text , ntext , image .型数据不可用。
范围说明: between A and B, not between A and B.
可选值列表: in , not in .一般用于嵌套查询
模式匹配: like , not like .
是否空值: is null , is not null .
上述条件的逻辑组合: and , or , not
内容大小写敏感
like关键字的通配符
% ,0或多个字符组成的字符串
_,任意单个字符
[] ,用于指定范围,例: [ a-f ] a至f范围内的任意单个字符
[ ^ ] ,用于指定范围,例: [ ^a-f ] a至f范围以外的任意单个字符
like ' mc% '
like ' %inger '
like ' _hery1 '
like ' [m-z]inger '
like ' m[^c]% '
like ' %en% '
查询数值:
字段 beteen 2 and 5
字段 > 7000
查询特定数值:
字段 in ( ' 1001 ' , ' 1003 ' )
查询name
字段 like ' 王__ '
通配符的转义字符
# escape ' # ' 定义转义字符
例: 字段 like ' sql#_m_il ' escape ' # '
用 [] 将通配符指定为普通字符
例: 字段 like ' %54[%]% '
嵌套查询
定义:
1 .指在一个外层查询中包含有另一个内层查询。其中外层查询称为主查询,内层查询称为子查询。
2 .SQL允许多层嵌套,由内而外地进行分析,子查询的结果作为主查询的查询条件
3 .子查询中一般不使用order by子句,只能对最终查询结果进行排序
子查询(sub query)
where 表达式 [ not ] in (子查询)
where 表达式 比较运算符 [ any|all ] 子查询
where [ not ] exists (子查询)
1 .子查询-单值比较
返回单值子查询,只返回一行一列
主查询与单值子查询之间用比较运算符进行连接:
运算符: > , >= , < , <= , = , <>
例:找出与太行同龄的同事
select * from company
where age = ( select age from company
where name = taihang)
2 .子查询- in
例:查询选修了‘ 001 ’课程的学生学号,姓名。
select id,name
from student
where id in ( select id
from taihang
where id = ' 001 ' )
3 .子查询-多值比较all
多行一列
1 .父查询与多值子查询之间的比较需用all来连接
2 .标量值S比子查询返回集R中的每个都大时,s >all ,r为true
3 .all表示所有
4 . >all , <all , >=all , <=all , <>all ,注:all等价于not in
例:找出年龄最小的学生
select * from student
where age <all ( select age from student)
4 .子查询-多值比较some /any
1 .父查询与多值子查询之间的比较需用some / any来连接
2 .标量值S比子查询返回集r中的某一个都大时,s > some时r为true 或s > any时r为true
3 .some表示部分
4 . >some , >=some , =some , <some , <=some , <>some ,注: = some等价于in, <> some不等价于not in .
例:找出不是最小年龄的学生
select * from student
where age > some ( select age from student)
5 .子查询-存在判断exists
1 . exists+ 子查询用来判断该子查询是否返回元组
2 .当子查询的结果集非空时,exists为true
3 .当子查询的结果集为空时,exists为false
4 .不关心子查询的具体内容,因此用select *
例:列出先修了C01课程的学习的学号,姓名
select son,sname
from strdent
where exists ( select * from sc
where sc.sno = stusent.sno and
cno = ' C01 ' )
最后这一个不是很好理解呀!等用多了就好了。