
SQL语句使用经典例子.doc
7页SQL 语句使用经典例子 一节、数据表的查询(select) select 字段列表 [as 别名 ], * from 数据表名[where 条件语句][group by 分组字段][order by 排序字段列表 desc][LIMIT startrow,rownumber]1、Select 字段列表 From 数据表例:①、select id,gsmc,add,tel from haf (* 表示数据表中所有字段)②、select 单价,数量,单价 *数量 as 合计金额 from haf (As 设置字段的别名)2、Select … from … Where 筛选条件式筛选条件式:①、字符串数据: select * from 成绩单 Where 姓名='李明'②、万用字符: select * from 成绩单 Where 姓名 like '李%'select * from 成绩单 Where 姓名 like '%李%'select * from 成绩单 Where 姓名 like '%李_'③、特殊的条件式:⑴= / > / / >= / ' %代表任意长度(长度可以为 0)的字符串 ; _代表任意单个字符,汉字得用两个"__"):14、查询学号为 95001 的学生的详细情况select * from student where son like '95001'15、查询所有姓名李的学生的姓名、学号和性别。
select sname,son,ssex from student where sname like '李%'16、查询姓名是两个字学生的姓名、学号和性别select sname,son,ssex from student where sname like '____'17、查询所有不姓李的学生姓名select sname from student where sname not like '李__'涉及空值的查询:18、某些学生选修课程后没有参加考试,所以有选课记录,但没有考试成绩,查询缺少成绩的学生的学号和相应的课程号select sno,cno from sc where grade is null19、查询所有有成绩的学生学号和课程号select sno,cno from sc where grade is not null多重条件查询(and or) :20、查询计算机系年龄在 20 岁的学生姓名select sname from student where sdept='cs' and sage=2021、查询信息系(is)、数学系 (ma)和计算机科学系(cs) 学生的姓名和性别。
select sname,ssex from student where sdept='is' or sdept='ma' or sdept='cs'三、对查询结果排序:22、查询选修了 3 号课程的学生的学号及其成绩,查询结果按分数的降序排列select sno,grade from sc where cno='3' order by grade desc 23、查询全体学生情况,查询结果按所在系的系号升序排列,同一系中的学生按年龄降序排列select * from student order by sdept,sage desc四、使用集函数:24、查询学生总人数select count(*) as '总人数' from student25、查询选修了课程的学生人数select count(distinct sno) as '人数' from sc26、计算 1 号课程的学生平均成绩select format(avg(grade),2) as '平均成绩' from sc where cno='1'27、查询选修 1 号课程的学生最高分数select max(grade) from sc where cno='1'五、对查询结果分组:28、求各个课程号及相应的选课人数。
select cno as '课程号',count(sno) as ' 人数' from sc group by cno29、查询选修了 3 门以上课程的学生学号select sno from sc group by sno having count(*)>2注:where 子句与 having 短语的区别在于作用对象不同,where 子句作用于基本表或视图,从中选择满足条件的记录,having 短语作用于组,从中选择满足条件的组多表查询同时查询两个以上的表,称为连接查询等值连接:当连接运算符为=时,为等值连接1、查询每个学生及其选修课程的情况(等值连接) select student.*,sc.* from student,sc where student.son=sc.sno自然连接:在等值连接中把目标列中重复的属性列去掉2、查询每个学生及其选修课程的情况(自然连接) select student.son,sname,ssex,sage,sdept,cno,grade from student,sc where student.son=sc.sno自身连接:连接操作不仅可以在两个表之间进行,也可以是一个表与其自己进行连接。
3、查询每一门课的间接先修课select o,b.cpno,ame from course a,course b where a.cpno=o复合条件连接:4、查询选修 2 号课程且成绩在 90 分以上的所有学生select a.son,sname from student a,sc b where a.son=b.sno and o='2' and b.grade>905、查询每个学生的学号、姓名、选修的课程名及成绩select a.son,sname,cname,grade from student a,sc b ,course c where a.son=b.sno and o=ogoogle_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);。












