--目标表达式还可以是函数
select COUNT(Sname)
from student;
--指定distinct关键词可以消除重复的行,否则将输出所有的行
--查询选修了课程的学生学号
select distinct sno
from sc;
--查询选修了计算机科学系全体学生的名单
select sname
from student
where sdept='CS';
--查询所有年龄在20岁以下的学生姓名及其年龄
select sname,sage
from student
where sage<20;
--查询考试成绩有不及格的学生的学号
select distinct sno
from sc
where grade<60;
--查询性别为女的学生的学号和姓名
select sno,sname
from student
where ssex='女';
--查询学分为4学分的课程
select cname
from course
where ccredit>=4;
--查询成绩在85分以上的学生学号
select distinct sno
from sc
where grade>85;
--查询年龄在20-23之间的学生姓名、性别和年龄
select sname,ssex,sage
from student
where sage>=20 and
sage<=23;
select sname
from student
where sage between 20 and 23;
--查询年龄不在20~23岁之间的学生姓名、系别和年龄
select sname,sdept,sage
from student
where sage<20 and
sage>23;
select sname
from student
where sage not between 20 and 23;
--查询CS、MA、IS学生的姓名和性别
select sname,ssex
from student
where sdept in('CS','MA','IS');
--查询既不是计算机科学系、数学系,也不是信息系的学生的姓名和性别。
select sname,ssex
from student
where sdept not in('IS','MA');
--%代表任意长度的字符串(长度可以是0):a%b表示以a开头以b结尾的任意长度的字符串
-- _下划线表示任意单个字符:a_b表示以a开头以b结尾的长度为3的字符串
--查询学号为201215121的学生的详细情况。
select *
from student
where sno like '21';
select *
from student
where sno='21';
--查询所有姓刘学生的姓名、学 号和性别。
select sname,sno,ssex
from student
where sname like'刘%';
--查询姓"欧阳"且全名为三个汉字的 学生的姓名。
select sname
from student
where sname like '欧阳_';
--查询名字中第2个字为"阳"字 的学生的姓名和学号
select sname
from student
where sname like '_阳%';
--查询所有不姓刘的学生姓名、学号 和性别。
select sname
from student
where sname not like'刘%';
--将通配字符转换成普通字符,用escape声明转义字符是谁
--查询DB_Design课程的课程号和学分
select cno,ccredit
from course
where cname like'DB\_Design' escape'\';
--查询以“DB_”开头且倒数第三个字符为i的课程的详细情况
select *
from course
where cname like'DB\_%i_ _' escape'\';
--is null中的is不能用“=”来代替
--某些学生选修课程后没有参加考试,所以有选课记录,但没 有考试成绩。 查询缺少成绩的学生的学号和相应的课程号
select sno,cno
from sc
where grade is null;
--查所有有成绩的学生学号和课程号。
select sno,cno
from sc
where grade is not null;
--and 和 or可以用来连接多个查询条件,其中and的优先级要高于or
--查询计算机系年龄在20岁以下的学生姓名
select sname
from student
where sdept='CS' and
sage<20;
--查询计算机科学系(CS)、数学系(MA)和信息系(IS)学生的姓名和性别
select sname,ssex
from student
where sdept='CS' or
sdept='IS' or
sdept='MA';
select sname,ssex
from student
where sdept in('CS','MA','IS');
--升序:ASC 降序:DESC
--对于空值的排序显示的排序次序有具体的DBMS来决定
--查询选修了3号课程的学生的学号及其成绩,查询结果按分数降序排列。
select sno,grade
from sc
where cno=3
order by grade ASC;
select sno,grade
from sc
where cno=3
order by grade;
--查询全体学生情况,查询结果按所在系 的系号升序排列,同一系中的学生按年龄降序排 列。
select *
from student
order by sdept,sage DESC;
--聚集函数:
--1.查询学生总数
select COUNT(*)
from student;
--2.查询选修了课程的学生人数
select COUNT(distinct sno)
from sc;
--3.计算1号课程的平均成绩
select AVG(grade)
from sc
where cno=1;
--4.查询选修1号课程的学生最高分数。
select MAX(grade)
from sc
where cno=1;
--5.查询学生201215012选修课程的总学分数。
select SUM(ccredit)
from sc,course
where sc.cno=course.cno and
sno='21';
数据库常用语法
最新推荐文章于 2022-06-05 21:04:08 发布