sql-语句

like

Exists子句只返回true值,Not Exists只返回false值。的用法

设教学数据库Education有三个关系:

学生关系S(Sno,Sname, Ssex,Sage,Sdept);

学习关系SC(Sno,Cno,Grade);

课程关系C(Cno,Cname,Cdept,Tname)

 

查所年龄在20至23岁之间的学生姓名、系别及年龄。

select Sname,Sdept,Sage
from S
where Sage between 20 and 23

查缺考的学生的学号和课程号。

select Sno,Cno
from SC
where Grade is null

查询全体学生的情况,查询结果按所在系升序排列,对同一系中的学生按年龄降序排列。

select *
from S
order by Sdept asc,Sage desc

检索至少选修课程号为C2和C4的学生学号; (子查询)

select Sno
from SC
where Cno='C2' and Sno in
(select Sno
from SC
where Cno='C4')

检索学习全部课程的学生姓名;

//Exists子句只返回true值,Not Exists只返回false值。

select Sname
from S
where not exists
(select * from C
where not exists
(select * from SC
where S.Sno=SC.Sno and SC.Cno=C.Cno))

//查找学习了所有课程的学生,即是在C中不存在一门课程没有学。

 

查询计算机系选修了3门以上课程的学生的学号。

select S.Sno
from S,SC
where S.Sdept='CS' and S.Sno=SC.Sno
group by S.Sno
having count(*)>3

 

16、求基本表S中男同学的每一年龄组(超过50人)有多少人?要求查询结果按人数升序排列,人数相同按年龄降序排列。

select Sage,count(Sno)
from S
group by Sage
having count(*)>50
order by count(*) asc,Sage desc

 

统计每一年龄选修课程的学生人数。

select Sage,count(distinct S.Sno)
from S,SC
where S.Sno=SC.Sno
group by S.Sage

 

查询全部学生的成绩 成绩为0分的用*代替,缺考的用_代替

SELECT name,CASE score.score WHEN  0 THEN '*' ELSE  IFNULL(score.score,'_') END AS score  FROM student LEFT JOIN score ON student.id=score.stu_id;

posted @ 2023-10-26 16:25  ~技术小白  阅读(30)  评论(0编辑  收藏  举报