select sno,count(*) from grades
where mark<60
group by sno
having count(*)>1
6.UNION联合
合并查询结果,如:
SELECT * FROM students
WHERE name like ‘张%’
UNION [ALL]
SELECT * FROM students
WHERE name like ‘李%’
7.多表查询
a.内连接
select g.sno,s.name,c.coursename
from grades g JOIN students s ON g.sno=s.sno
JOIN courses c ON g.cno=c.cno
(注意可以引用别名)
b.外连接
b1.左连接
select courses.cno,max(coursename),count(sno)
from courses LEFT JOIN grades ON courses.cno=grades.cno
group by courses.cno
左连接特点:显示全部左边表中的所有项目,即使其中有些项中的数据未填写完全。
左外连接返回那些存在于左表而右表中却没有的行,再加上内连接的行。
b2.右连接
与左连接类似
b3.全连接
select sno,name,major
from students FULL JOIN majors ON students.mno=majors.mno
两边表中的内容全部显示
c.自身连接
select c1.cno,c1.coursename,c1.pno,c2.coursename
from courses c1,courses c2 where c1.pno=c2.cno
采用别名解决问题。
d.交叉连接
select lastname+firstname from lastname CROSS JOIN firstanme
相当于做笛卡儿积
8.嵌套查询
a.用关键字IN,如查询李山的同乡:
select * from students
where native in (select native from students where name=’ 李山’)
b.使用关键字EXIST,比如,下面两句是等价的:
select * from students
where sno in (select sno from grades where cno=’B2’)
select * from students where exists
(select * from grades where
grades.sno=students.sno AND cno=’B2’)
9.关于排序order
a.对于排序order,有两种方法:asc升序和desc降序
b.对于排序order,可以按照查询条件中的某项排列,而且这项可用数字表示,如:
select sno,count(*) ,avg(mark) from grades group by sno having avg(mark)>85 order by 3