回顧MySQL查詢語句經典例項3
阿新 • • 發佈:2021-02-02
技術標籤:Java Web技術解析MySQLMySQLSQL
#查詢姓氏是李的老師的數量
select count(*) as nameNum
from teacher
where tname like '李%';
#查詢學習過張三老師課程的學生資訊
#多表聯合查詢
select student.* from student,teacher,course,score where student.sid = score.sid and course.cid=score.cid and course.tid = teacher.tid and tname = '張三';
#查詢沒有學習所有課程的同學資訊
#因為有學生什麼課都沒有選,反向思考,先查詢選了所有課的學生,再選擇這些人之外的學生.
select * from student
where student.sid not in (
select score.sid from score
group by score.sid
having count(score.cid)= (select count(cid) from course)
);
#查詢至少有一門課程與學號為“01”的同學所學相同的同學的資訊
select * from student where student.sid in ( select score.sid from score where score.cid in( select score.cid from score where score.sid = '01' )
#查詢沒有學過張三老師的任一門課的學生姓名
#巢狀查詢
select * from student where student.sid not in( select score.sid from score where score.cid in( select course.cid from course where course.tid in( select teacher.tid from teacher where tname = "張三" ) ) );
#查詢兩門及其以上不及格課程的同學的學號,姓名及其平均成績
select student.sid, student.sname,b.avgScore
from student RIGHT JOIN
(select sid, AVG(score) as avgScore from score
where sid in (
select sid from score
where score<60
GROUP BY sid
HAVING count(score)>1)
GROUP BY sid) b on student.sid=b.sid;
#檢索" 01 "課程分數小於 60,按分數降序排列的學生資訊
select student.*, score.score from student, score
where student.sid = score.sid
and score.score < 60
and cid = "01"
ORDER BY score.score DESC;