我们在软件开发过程中,或多或少都会接触到数据库的开发,下面我就以学生信息表为例表把常用的数据库的查询语言进行一个总结:
1、查询全体学生的学号、姓名和年龄:select sno,sn ,age from s
2、查询学生的全部信息:select * from s
3、查询选修了课程的学生的学号:select distinct sno from sc
4、查询全体学生的姓名、学号和年龄:select sn name, sno ,age from s或select sn as name, sno, age from s
条件查询:需要用where子句指定查询条件
条件部分:1)列名 2)比较运算符 3)列名(常数)
常用的比较运算符:
比较大小:=,>,<,>=,<=,!=,<>
多重条件:and,or,not
确定范围:between and
确定集合:in
字符匹配:like
5、查询选修课程号为'c1'的学生的学号和成绩:select sno, score from sc where cno='c1'
6、查询成绩高于85分的学生的学号、课程号和成绩:select sno, cno, score from sc where score>85
多重条件查询:where子句指定一个以上的查询条件,需使用逻辑运算符and、or、not,将其连接成复合逻辑表达式,优先级由高到低:not、and、or。
7、查询选修c1或c2且分数大于等于85分学生的学号、课程号和成绩:select sno, cno, score from sc where (cno='c1' or cno = 'c2')and(score>=85)
确定范围:
8、查询工资在1000元—1500元之间教师的教师号、姓名及职称:select tno, tn, prof from t where scal between 1000 and 1500
确定集合:利用“in”操作可以查询属性值属于指定集合的元组
select sno, cno, score from sc where cno='c1' or cno='c2'
利用“not in”可以查询指定集合外的元组
select sno, cno, score from sc where (cno<>'c1') and (cno<>'c2')
部分匹配查询:当不知道完全精确的值时,用户还可以使用like或not like进行部分匹配查询(模糊查询)
like用法:<属性名> like <字符串常量>
字符串中可以含有的通配符:
%:代表0个或多个字符串 'ab%':'ab'后可接任意字符串
_:代表一个字符 'a_b':'a'与'b'之间可有一个字符
[ ]:表示在某个范围的字符 [0~9]:0~9之间的字符
0~9之间的字符
11、查询所有姓张的教师的教师号和姓名:select tno, tn from t where tn like '张%'
12、查询姓名中第二个汉字是“力”的教师号和姓名:select tno, tn from t where tn like '_力%'
空值查询:某个字段没有值称之为具有空值(null)
13、查询没有考试成绩的学生的学号和相应课程号:select sno, cno from sc where score is null
常用库函数及统计汇总查询:
按列计算平均值:avg
按列计算值的总和:sum
求一列中的最大值:max
求一列中的最小值:min
按列值统计个数:count
14、求学号为s1的学生总分和平均分:select sum(score) as totalscore, avg(score) as avgscore from sc where (sno='s1')
15、求选修c1号课程的最高分、最低分及它们之间相差的分数:select max(score) as maxscore, min(score) as minscore,max(score)-min(score) as diff from sc where (cno='c1')
16、求计算机系学生的总数:select count(sno) from s where dept='计算机'
17、求学校中共有多少个系:select count(distinct dept) as deptnum from s
18、统计有成绩学生的人数:select count(score) from sc
19、利用特殊函数count(*)求计算机系学生的总数:select count(*) from s where dept='计算机'
分组查询:group by子句可将查询结果按属性列或属性列组合在行的方向上进行分组,每组在属性列或属性列组合上具有相同的值
20、查询每个教师的教师号及其任课的门数:select tno count(*) as c_num from tc group by tno
若在分组后还要按照一定条件筛选,则需使用having子句
21、查询选修两门以上(含两门)课程的学生的学号和选课门数:select sno, count(*) as sc_num from sc group by sno having (count(*)>=2)
查询的排序:当需要对查询结果排序时,应使用order by子句(出现在其他子句后),排序方式可以指定:降序desc、升序asc(默认升序)
22、查询选修c1的学生学号和成绩,并按成绩降序排列:select sno, score from sc where (cno='c1') order by score desc
23、查询选修c2、c3、c4或c5课程学生的学号、课程号和成绩,查询结果按学号升序排列,学号相同时再按成绩降序排列:
select sno, cno, score from sc where (cno in ('c2', 'c3', 'c4', 'c5')) order by sno, score desc
24、求选修在三门以上(含三门)且各门课程均及格的学生及其总成绩,查询结果按总成绩降序排列:select sno, sum(score) as tatalscore from sc where (score>=60) group by sno having (count(*)>=3) order by sum(score) desc
先总结到这,后续再做补充。