Select 子句
from子句:指定查询数据的表
where子句:查询数据的过滤条件
group by子句:对匹配where子句的查询结果进行分组
having子句:对分组后的结果进行条件限制
order by子句:对查询结果结果进行排序,后面跟desc降序或asc升序(默认)。
limit子句:对查询的显示结果限制数目
procedure子句:查询存储过程返回的结果集数据
举例1 : 查询全体学生的学号与姓名。
select sno,sname from student;
举例2 : 查询全体学生的详细记录。
select sno,sname,ssex,sage,sdept from student;
或select * from student;
举例3 : 查全体学生的姓名及其出生年份。
select sname,2008-sage from student;
举例4 : 查询全体学生的姓名、出生年份和所有系,要求用小写字母表示所有系名。
select sname,'year of birth: ',2008-sage, islower(sdept) from student;
举例5 : 查询选修了课程的学生学号(去掉重复的记录)
select distinct studentid from sc;
举例6 : 查询全体学生的学号与姓名,用中文显示列名。
select sno as ‘编号’,sname as ‘姓名’ from student;
举例7 : 给表设置别名。
select s.sno,s.sname from student as s;
举例8 : 查询年龄在20以下的学生的姓名。
select sname from student where sage<20;
举例9 : 查询全体学生的姓名、年龄,要求按照年龄降序排序。
select sname,sage from student order by sage desc;
举例10 : 查询年龄最大的前3个学生的姓名和年龄,或第4、5个学生
select sname,sage from student order by sage desc limit 3;或(limit 3,2)
举例11 : 查询学生总数。 select count(*) from student;
举例12 : 查询选修了课程的学生人数。 select count(distince studentid) from sc;
举例13 : 查询1号课程的学生平均成绩。 select avg(grade) from sc where courseid=1;
举例14 : 查询1号课程的学生最高分和最低分。
select max(grade) as ‘最高分’,min(grade) as ‘最低分’ from sc where courseid=1;
举例15 : 查询每个学生的平均成绩。
select studentid,avg(grade) as ‘平均成绩’ from sc group by studentid;
举例16 : 查询学生的平均成绩在70分以上的。
select studentid,avg(grade) as ‘平均成绩’ from sc group by studentid having avg(grade)>70;
举例17 : 查询年龄在20~23岁(包括20岁和23岁)之间的学生的姓名、系别和年龄 。
select sname,sdept,sage from student where sage between 20 and 23;
举例18 : 查询年龄不在20~23岁之间的学生姓名、系别和年龄。
select sname,sdept,sage from student where sage not between 20 and 23;
举例19 : 查询'信息系'、'美术系'和'计算机系'学生的姓名和性别。
select sname,ssex from student where sdept in (‘信息系',‘美术系',‘计算机系');
举例20 : 查询学号为95001的学生的详细情况。
select * from student where sno like '95001';
等价于:select * from student where sno='95001';
举例21 : 查询所有姓刘学生的姓名、学号和性别。
select sname,ano,ssex form student where sname like ‘刘%';
举例22 : 某些学生选修课程后没有参加考试,所以有选课记录,但没有考试成绩。查询缺少成绩的学生的学号和相应的课程号。
select studentid,courseid from sc where grade is null;
举例23 : 查所有有成绩的学生学号和课程号。
select studentid,courseid from sc where grade is not null;
举例24 : 查询计算机系年龄在20岁以下的学生姓名。
select sname from student where sdept=‘计算机系' and sage<20;
举例25 : 查询信息系、美术系和计算机系学生的姓名和性别
select sname,ssex from student where sdept in (‘信息系','美术','计算机系');
可改写为:
Select sname,ssex from student where sdept='信息系' or sdept='美术' or sdept='计算机系';
举例26 : 查询选修了3号课程的学生的学号及其成绩,查询结果按分数降序排列。
select studentid,grade from sc where courseid=3 orber by grade desc;
举例27 : 查询全体学生情况,查询结果按所在系的系号升序排列,同一系中的学生按年龄降序排列。
select * from student order by sdept,sage desc;