数据的查询
单表查询
- 查询全体学生的学号和姓名 :
select Sno,Cno from sc;
select * from sc;
目标表达式不仅可以是表中的属性列,也可以是表达式没字符串常量、函数等 别名(aliases)。
查询全体学生的姓名及出生年份:
select Sname Sage-2014 from sc;//查询结果的第二列是一个算术表达式
select LOWER(cname) from course;//使cname都小写。
select LOWER(cname) 小名 from course;
- 删除重复行(distinct 默认是all)
select distinct Sno from sc;
- between…and…。
select Sname,Sdept,Sage from student where Sage
between 20 and 30;
查询年龄在20~30岁[包括20、30]之间的学生的姓名、系别、年龄)
in 可以确定集合 可以用来查找属性值属于指定集合的元组
select Sname,Ssex from student where Sdept in('CS','MA','IS');
//查询cs ma is学生的姓名和性别。
- ike ,not like
- %代表任意长度的字符串
- _代表任意单个字符。
- \代表转义字符
select * from student where sno like 'a%b';
//查询 以a开头以b结尾的任意长度字符串
select * from student where sname like '刘%';
// 查询姓刘的学生的姓名、学号、班级
select * from student where Cname like 'DB\_%i__';
// 查询以“DB_”开头,且倒数第三个字符为i的课程的详细情况
- NULL NOT NULL
//查询 分数为空的学生学号和姓名。
select Sno,Cno from student where grade is null;
- AND 和 or and优先级高于or,但是用户可以用括号改变优先级。
// 查询cs系在年龄20岁以下的学生姓名。
select sname from student where sdept='CS' and Sage<20;
- order by 排序 asc升序 desc 降序
聚集函数 只能用于select 子句和group by 中的having子句 - count(*) 统计元组个数
-count([distanct|all]<列名>) 一列中值的总个数
-sum([distanct|all]<列名>) 一列值中的总和 - avg([distanct|all]<列名>) 一列值中的平均值
- max([distanct|all]<列名>) 一列值中的最大值
- min([distanct|all]<列名>) 一列之中的最小值
统计一列中的值的个数
select count(*) from student;
// 查询学生总人数
select count(distinct sno) from sc;
//查询选修了课程的学生人数。
select avg(grade) from sc where cno='1';
// 计算选修一号课程的学生的最高分数。
- group by 分组后聚集函数将作用于每一个组,即每一组都有一个函数。
select Cno,count(Sno) from sc group by cno;
//查询各个课程号及相应的选课人数
select sno from sc group by cno having count(*)>3;
//查询选修了三门以上课程的学生学号
where子句和having短语的区别在于作用的对象不同。where子句作用于基本表或者视图,having短语作用于组。
再次强调:聚集函数只能于select子句和group by中的having子句。