--2007-6-18 18:38:39
SQL系统复习
简单查询选择列
查询所有的记录
select * from scott.emp
查询所有记录的某些字段
select empno,ename,job from scott.emp
查询某些字段不同记录
select distinct job from scott.emp
这里的“distinct”保留字指在显示时去除相同的记录,与之对应的是“all”将保留相同的记录,默认为“all”。
选择行
单条件过滤
select empno,ename,job from scott.emp where job ='MANAGER'
select empno,ename,sal from scott.emp where sal<=2500
单条件查询使用的比较运算符
=(等于)
!= (不等于)
^=(不等于)
<>(不等于)
<(小于)
>(大于)
<=(小于等于)
>=(大于等于)
in(列表)
not in(不在列表)
between(介于之间)
not between (不介于之间)
like(模式匹配) (like和not like适合字符型字段的查询,%代表任意长度的字符串,_下划线代表一个任意的字符。)
not like (模式不匹配)
Is null (是否为空)
is not null(是否为空)
组合条件过滤
select empno,ename,job from scott.emp where job>='CLERK' and sal<=2000
select empno,ename,job from scott.emp where not job='CLERK'
逻辑比较符
and(与) or (或) not(非)
排序结果
select empno,ename,job from scott.emp where job<='CLERK' order by job asc,sal desc
asc代表升序排列,desc代表降序排列,多个排序字段之间通过逗号分割。
分组结果
分组查询是指将查询结果按照字段分组。
下面列出留言本中留言超过十条的所有人,并按留言数递减排序。
select guestbook.posterid,classmates.name,count(guestbook.postid) from guestbook inner join
classmates on guestbook.posterid = classmates.id
group by classmates.name,guestbook.posterid having count(guestbook.postid)>10 order by count(guestbook.postid) desc
输出字段中的非聚合字段必须出现在group by子句里。输出结果:
7 涛哥 38
21 朱宇 35
24 谢计可 23
1 建文 21
103 阚军伟 20
11 1 19
3 任龙 11
where检查每条记录是否符合条件,having是检查分组后的各组是否满足条件。
联接查询
无条件联接
无条件联接查询是将各表的记录以“笛卡尔”积的方式组合起来。
如scott.dept表共有4条记录,scott.emp表共有14条记录,其“笛卡尔”积将有4*14=56条记录。
select emp.empno,emp.ename,emp.deptno,dept.dname,dept.loc from scott.emp,scott.dept
条件联接
Where子句联(下面的结果与内联结果是一样的)
-- Join in Where clause.
USE pubs
Select t.title_id, t.title, s.qty
FROM titles AS t, sales AS s
Where t.title_id *= s.title_id
From 子句联(就是Join联接)
内联接(INNER JION )
Select t.title_id, t.title, s.qty FROM titles AS t INNER JION sales AS s ON t.title_id *= s.title_id
外联接(OUTER JOIN)
Select a.au_fname, a.au_lname, p.pub_name
FROM authors a LEFT OUTER JOIN publishers p
ON a.city = p.city
orDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC
注:在内部连接中,参与连接的表的地位是平等的。在外部连接中,参与连接的表有主从之分,以主表的每行数据去匹配从表的数据列,符合连接条件的数据将直接返回到结果集中,对那些不符合连接条件的列,将被填上NULL 值后再返回到结果集中。
交叉联接(CROSS JOIN)
多种联接形式不一,却可互换,不说了这个。
相关内容
下列内容与有着内在的联系,建议您一并阅读。