目录 1.建库建表2.插入数据3.SQL 50 题3.1.✨SQL 01——查询"01"课程比"02"课程成绩高的学生的信息及课程分数3.2.SQL 02——查询"01"课程比"02"课程成绩
① 本文整理了经典的 50 道 sql 题目,文本分为建库建表、插入数据以及 SQL 50 题这三个部分。
② 本文所使用的 Mysql 版本为 5.5,虽然版本有一点旧,但是对 SQL 知识点的复习没有太大的影响(除了一些旧版没有的函数)。
③ 由于本文旨在对 SQL 基础知识进行复习,并且所涉及的数据量也十分的小,所以在编写 SQL 语句时,并未过多考虑 SQL 优化的方面。如果读者有其它的解法或者发现错误之处,可在评论区留言,笔者在看到后会及时更新!
(1)建库:创建一个名为 sqlpractice 的数据库。
(2)建表:建立 student、course、teacher 和 score 这 4 张表。它们的字段以及之间的关系如下图所示。
(3)建库建表的完整 SQL 语句如下所示。
# 建库create database sqlpractice;use sqlpractice;# 建立 Student 学生表CREATE TABLE Student(s_id VARCHAR(20),s_name VARCHAR(20) NOT NULL,s_birth VARCHAR(20) NOT NULL, s_sex VARCHAR(10) NOT NULL,PRIMARY KEY(s_id)# 主键);# 建立 Course 课程表CREATE TABLE Course(c_id VARCHAR(20),c_name VARCHAR(20) NOT NULL,t_id VARCHAR(20) NOT NULL,PRIMARY KEY(c_id)# 主键);# 建立 Teacher 教师表CREATE TABLE Teacher(t_id VARCHAR(20),t_name VARCHAR(20) NOT NULL DEFAULT '',PRIMARY KEY(t_id)# 主键);# 建立 Score 分数表CREATE TABLE Score(s_id VARCHAR(20),c_id VARCHAR(20),s_score INT(3),PRIMARY KEY(s_id, c_id) # 联合主键);# 添加外键# 语法:ALTER TABLE 从表 ADD FOREIGN KEY(外键字段) REFERENCES 主表(主键字段)ALTER TABLE Course ADD FOREIGN KEY(t_id) REFERENCES Teacher(t_id)ALTER TABLE Score ADD FOREIGN KEY(s_id) REFERENCES Student(s_id)ALTER TABLE Score ADD FOREIGN KEY(c_id) REFERENCES Course(c_id)
(1)向上面创建的 4 张表中插入测试数据的 SQL 语句如下所示(需要注意表之间的关系,以免插入数据失败)。
# 分别向四张表中插入数据INSERT INTO Student VALUES('01', '赵雷', '1990-01-01', '男');INSERT INTO Student VALUES('02', '钱电', '1990-12-21', '男');INSERT INTO Student VALUES('03', '孙风', '1990-05-20', '男');INSERT INTO Student VALUES('04', '李云', '1990-08-06', '男');INSERT INTO Student VALUES('05', '周梅', '1991-12-01', '女');INSERT INTO Student VALUES('06', '吴兰', '1992-03-01', '女');INSERT INTO Student VALUES('07', '郑竹', '1989-07-01', '女');INSERT INTO Student VALUES('08', '王菊', '1990-01-20', '女');INSERT INTO Teacher VALUES('01', '张三');INSERT INTO Teacher VALUES('02', '李四');INSERT INTO Teacher VALUES('03', '王五');INSERT INTO Course VALUES('01', '语文', '02');INSERT INTO Course VALUES('02', '数学', '01');INSERT INTO Course VALUES('03', '英语', '03');INSERT INTO Score VALUES('01', '01', 80);INSERT INTO Score VALUES('01', '02', 90);INSERT INTO Score VALUES('01', '03', 99);INSERT INTO Score VALUES('02', '01', 70);INSERT INTO Score VALUES('02', '02', 60);INSERT INTO Score VALUES('02', '03', 80);INSERT INTO Score VALUES('03', '01', 80);INSERT INTO Score VALUES('03', '02', 80);INSERT INTO Score VALUES('03', '03', 80);INSERT INTO Score VALUES('04', '01', 50);INSERT INTO Score VALUES('04', '02', 30);INSERT INTO Score VALUES('04', '03', 20);INSERT INTO Score VALUES('05', '01', 76);INSERT INTO Score VALUES('05', '02', 87);INSERT INTO Score VALUES('06', '01', 31);INSERT INTO Score VALUES('06', '03', 34);INSERT INTO Score VALUES('07', '02', 89);INSERT INTO Score VALUES('07', '03', 98);
(2)检验插入数据是否成功
SELECT * FROM Student;SELECT * FROM Course;SELECT * FROM Teacher;SELECT * FROM Score;
Student 表
Course 表
Teacher 表
Score 表
# 本题需要比较"01"课程比"02"课程的成绩,故在 where 中将 score 表中的字段 s_score 使用 2 次(即分别对应"01"课程的成绩和"02"课程的成绩)# 所以可以使用为 s_score 表取别名的方式来多次使用 score 表中的字段SELECTstudent.*,score1.s_score FROMstudent,score AS score1,score AS score2 WHEREstudent.s_id = score1.s_id AND score1.s_id = score2.s_id # student, score1, score2 表连接的条件是它们的 s_id 均相等AND score1.c_id = '01' AND score2.c_id = '02' AND score1.s_score > score2.s_score;
SELECTstudent.*,score1.s_score FROMstudent,score AS score1,score AS score2 WHEREstudent.s_id = score1.s_id AND score1.s_id = score2.s_id # student, score1, score2 表连接的条件是它们的 s_id 均相等AND score1.c_id = '01' AND score2.c_id = '02' AND score1.s_score < score2.s_score;
# 1.创建临时表 ssEXPLaiN SELECTstudent.s_id,student.s_name,ss.avg_score FROMstudent,(SELECT s_id, AVG(s_score) AS avg_score FROM score GROUP BY s_id) AS ss WHEREstudent.s_id = ss.s_id AND ss.avg_score >= 60;# 2.先进行内连接,然后再分组SELECTstudent.s_id,s_name,round(AVG(score.s_score), 2) as avg_scoreFROMstudentINNER JOIN score ON student.s_id = score.s_id GROUP BYstudent.s_id,s_name HAVINGAVG(score.s_score) >= 60
# isnull(exper) 判断 exper 是否为空,是则返回 1,否则返回 0# ifnull(exper1, exper2) 判断 exper1 是否为空,是则用 exper2 代替# nullif(exper1, exper2) 如果 expr1 = expr2 成立,那么返回值为 NULL,否则返回值为 expr1。SELECTstudent.s_id,s_name,round(AVG(score.s_score), 2) as avg_scoreFROMstudentLEFT OUTER JOIN score ON student.s_id = score.s_id GROUP BYstudent.s_id,s_name HAVINGAVG(IFNULL(score.s_score,0)) < 60
SELECTstudent.s_id,student.s_name,COUNT(DISTINCT c_id) AS totalCourses,SUM(s_score) AS totalScores FROMstudent# 由于要查询所有的学生,故无论其是否有课程信息都要查询,所以使用 LEFT OUTER JOINLEFT OUTER JOIN score ON student.s_id = score.s_id GROUP BYstudent.s_id,student.s_name;
# 1.模糊查询SELECTCOUNT(*) FROMteacher WHEREt_name LIKE '李%'# 2.正则表达式查询,字符 '^' 匹配以特定字符或者字符串开头的文本SELECTcount(*) FROMteacher WHEREt_name REGEXP '^李'
# 1.使用多表连接(score, course, teacher)找到上张三老师课的同学的 s_id,然后再根据 s_id 从 student 表中查询同学信息SELECTstudent.* FROMstudent WHEREs_id IN (SELECTs_id FROMscore,course,teacher WHEREteacher.t_name = '张三' AND teacher.t_id = course.t_id AND course.c_id = score.c_id )# 2.多层嵌套子查询(当数据量较大时,一般不推荐使用子查询)# 在 student 表中根据上过张三老师教的课的学生 s_id 来查询他们的信息SELECTstudent.* FROMstudent WHEREstudent.s_id IN (# 在 score 表中根据张三老师教的课程 c_id 来查找上这些课的学生 s_idSELECT DISTINCTs_id FROMscore WHEREscore.c_id IN (# 在 course 表中根据张三老师的 t_id 查询他所教的课程 c_idSELECT c_id FROM course WHERE course.t_id = (# 在 teacher 表中查询张三老师的 t_idSELECT t_id FROM teacher WHERE t_name = '张三')))
SELECTstudent.* FROMstudent WHEREstudent.s_id NOT IN (SELECT DISTINCTs_id FROMscore WHEREscore.c_id IN (SELECT c_id FROM course WHERE course.t_id = (SELECT t_id FROM teacher WHERE t_name = '张三')))
SELECTstudent.* FROMstudent WHEREstudent.s_id IN (SELECTs1.s_id FROMscore AS s1,score AS s2 WHEREs1.s_id = s2.s_id AND s1.c_id = '01' AND s2.c_id = '02' )
SELECTstu.s_id,stu.s_name,stu.s_birth,stu.s_sex FROMstudent AS stuJOIN score AS sc ON stu.s_id = sc.s_idJOIN course AS co ON co.c_id = sc.c_id WHEREco.c_id = '01' AND stu.s_id NOT IN (# 查询学过编号为 "02" 的课程的同学 idSELECTstu.s_idFROMstudent AS stuJOIN score AS sc ON stu.s_id = sc.s_idJOIN course AS co ON co.c_id = sc.c_id WHEREco.c_id = '02' )
# 下面的课程数量 3 也可以用 (SELECT count(*) FROM course) 来代替SELECT* FROMstudent WHEREs_id IN (SELECT s_id FROM score GROUP BY s_id HAVING count(c_id) < 3)
# 不包括学号为 '01' 学生自己SELECT* FROMstudent WHEREs_id IN (SELECT DISTINCT s_id FROM score WHERE c_id IN (SELECT c_id FROM score WHERE s_id = '01') AND s_id != '01')
SELECT* FROMstudent WHEREs_id IN (SELECTs_id FROMscore WHERE# 保证学习的课程相同c_id IN (SELECT DISTINCT c_id FROM score WHERE s_id = '01') AND s_id != '01' GROUP BYs_id HAVING# 保证学习的课程数量相同count(c_id) = (select count(*) from score where s_id = '01'))
SELECTs_name FROMstudent WHEREs_id NOT IN (# 查询学习过"张三"老师讲授的任一门课程的学生 idSELECTs_id FROMscore WHEREc_id IN ( # 查询由姓名为张三的老师所讲授的课程 idSELECTc_id FROMcourse WHEREt_id IN (SELECT t_id FROM teacher WHERE t_name = '张三')))
SELECTstu.s_id,stu.s_name,tmp_t.avg_score FROMstudent AS stuINNER JOIN (SELECT s_id, round(avg(s_score), 2) AS avg_score FROM score WHERE s_score < 60 GROUP BY s_id HAVING count(s_score) >= 2) AS tmp_t ON stu.s_id = tmp_t.s_id
SELECTstu.* FROMstudent AS stuINNER JOIN score ON stu.s_id = score.s_id WHEREc_id = '01' AND s_score < 60 ORDER BYs_score DESC
SELECTs_id,max(CASE c_id WHEN '01' THEN s_score ELSE 0 END) AS '01',max(CASE c_id WHEN '02' THEN s_score ELSE 0 END) AS '02',max(CASE c_id WHEN '03' THEN s_score ELSE 0 END) AS '03',avg(s_score) AS avg_score FROMscore GROUP BYs_id ORDER BYavg_score DESC
SELECTsc.c_id AS "课程ID",c.c_name AS '课程名称',MAX(sc.s_score) AS "最高分",MIN(sc.s_score) AS '最低分',AVG(sc.s_score) AS '平均分',SUM(IF (sc.s_score BETWEEN 60 AND 70, 1, 0)) / COUNT(*) as '及格率',SUM(IF (sc.s_score BETWEEN 70 AND 80, 1, 0)) / COUNT(*) as '中等率',SUM(IF (sc.s_score BETWEEN 80 AND 90, 1, 0)) / COUNT(*) as '优良率',SUM(IF (sc.s_score >= 90, 1, 0)) / COUNT(*) as '优秀率' FROMscore AS scJOIN course AS c ON sc.c_id = c.c_id GROUP BYsc.c_id
SELECTsc1.c_id,sc1.s_id,sc1.s_score,count(sc2.s_score) + 1 AS rank FROMscore AS sc1 LEFT JOIN score AS sc2 ON sc1.s_score < sc2.s_score AND sc1.c_id = sc2.c_id GROUP BYsc1.c_id,sc1.s_id,sc1.s_score ORDER BYsc1.c_id,rank
SELECT stu.s_id, stu.s_name, total_score, (SELECT COUNT(DISTINCT total_score) FROM (SELECT SUM(s_score) AS total_score FROM score GROUP BY s_id) AS sub WHERE total_score >= tmp.total_score) AS rankFROM student as stu INNER JOIN ( SELECT s_id, SUM(s_score) AS total_score FROM score GROUP BY s_id ) AS tmp ON stu.s_id = tmp.s_idORDER BY total_score DESC;
SELECTteacher.t_id,t_name,round(avg(s_score), 2) AS avg_score FROMteacher,course,score WHEREteacher.t_id = course.t_id AND course.c_id = score.c_id GROUP BYteacher.t_id,t_name,score.c_id ORDER BYavg(score.s_score) DESC
# 1.分别对每门课程进行查询,然后再合并查询结果,但是如果课程太多,该方法就不太合适SELECTt1.* FROM(SELECTst.*,c.c_id,c.c_name,sc.s_score FROMstudent stLEFT JOIN score sc ON sc.s_id = st.s_idINNER JOIN course c ON c.c_id = sc.c_id AND c.c_id = "01" ORDER BYsc.s_score DESC LIMIT 1,2 ) as t1UNION ALLSELECTt2.* FROM(SELECTst.*,c.c_id,c.c_name,sc.s_score FROMstudent stLEFT JOIN score sc ON sc.s_id = st.s_idINNER JOIN course c ON c.c_id = sc.c_id AND c.c_id = "02" ORDER BYsc.s_score DESC LIMIT 1,2 ) as t2UNioN ALLSELECTt3.* FROM(SELECTst.*,c.c_id,c.c_name,sc.s_score FROMstudent stLEFT JOIN score sc ON sc.s_id = st.s_idINNER JOIN course c ON c.c_id = sc.c_id AND c.c_id = "03" ORDER BYsc.s_score DESC LIMIT 1,2 ) as t3# 2.一次性查询,需要注意的是 row_number() 在 mysql 8.0 中才支持SELECTc_id,student.*,s_score FROMstudentINNER JOIN (SELECT s_id, s_score, c_id, row_number() over (PARTITION BY c_id ORDER BY s_score DESC) AS rank FROM score) AS tmp_t ON tmp_t.s_id = student.s_id WHEREtmp_t.rank IN (2, 3)
SELECTscore.c_id,course.c_name,sum(CASE WHEN s_score BETWEEN 0 AND 60 THEN 1 ELSE 0 END) AS '[0-60]人数',sum(CASE WHEN s_score BETWEEN 61 AND 70 THEN 1 ELSE 0 END) AS '[61-70]人数',sum(CASE WHEN s_score BETWEEN 71 AND 85 THEN 1 ELSE 0 END) AS '[71-85]人数',sum(CASE WHEN s_score BETWEEN 86 AND 100 THEN 1 ELSE 0 END) AS '[86-100]人数',round(sum(CASE WHEN s_score BETWEEN 0 AND 60 THEN 1 ELSE 0 END) / count(*), 2) AS '[0-60]人数所占百分比',round(sum(CASE WHEN s_score BETWEEN 61 AND 70 THEN 1 ELSE 0 END) / count(*), 2) AS '[61-70]人数所占百分比',round(sum(CASE WHEN s_score BETWEEN 71 AND 85 THEN 1 ELSE 0 END) / count(*), 2) AS '[71-85]人数所占百分比',round(sum(CASE WHEN s_score BETWEEN 86 AND 100 THEN 1 ELSE 0 END) / count(*), 2) AS '[86-100]人数所占百分比' FROMscore LEFT JOIN course ON score.c_id = course.c_id GROUP BYscore.c_id,course.c_name
# 在 MySQL 8 中可以使用 rank 函数来实现排名SELECT stu.s_id, stu.s_name, round(avg(sc.s_score), 2) AS average_score, (SELECT COUNT(DISTINCT avg_score) FROM (SELECT AVG(s_score) AS avg_score FROM score GROUP BY s_id) AS sub WHERE avg_score >= AVG(sc.s_score)) AS rankFROM student as stu INNER JOIN score as sc ON stu.s_id = sc.s_idGROUP BY stu.s_id, stu.s_nameORDER BY average_score DESC;
# 1.分别对每科进行查询,然后再合并查询结果,但是如果课程太多,该方法就不太合适(SELECT c_id, s_score FROM score WHERE c_id = '01' ORDER BY s_score DESC LIMIT 3) UNION ALL(SELECT c_id, s_score FROM score WHERE c_id = '02' ORDER BY s_score DESC LIMIT 3) UNION ALL(SELECT c_id, s_score FROM score WHERE c_id = '03' ORDER BY s_score DESC LIMIT 3)# 2.一次性查询出结果SELECT DISTINCTtmp_t.c_id,tmp_t.s_score FROM(SELECT DISTINCTstudent.*,sc1.c_id,sc1.s_score,count(DISTINCT sc2.s_score) + 1 AS rank FROMscore AS sc1LEFT JOIN score AS sc2 ON sc1.c_id = sc2.c_id AND sc1.s_score < sc2.s_scoreLEFT JOIN student ON sc1.s_id = student.s_id GROUP BYsc1.c_id,sc1.s_id ORDER BYsc1.c_id,sc1.s_score DESC ) AS tmp_t WHEREtmp_t.rank BETWEEN 1 AND 3
SELECTc_id,count( s_id ) AS '选修该门课程的学生数' FROMscore GROUP BYc_id
SELECTstudent.s_id,student.s_name FROMstudent,score WHEREstudent.s_id = score.s_id GROUP BYs_id HAVINGcount(c_id) = 2
SELECTsum(CASE WHEN s_sex = '男' THEN 1 ELSE NULL END) AS '男生人数',sum(CASE WHEN s_sex = '女' THEN 1 ELSE NULL END) AS '女生人数' FROMstudent
# 1.使用模糊匹配SELECT* FROMstudent WHEREs_name LIKE '%风%'# 2.使用正则表达式SELECT* FROMstudent WHEREs_name REGEXP '风'
在 MySQL 中,LIKE 操作符用于在文本字段中搜索特定的模式。如果需要在文本字段中匹配通配符本身,可以使用反斜杠字符转义通配符。例如,如果要在一个名为 ’mytable’ 的表中查找包含下划线字符的字符串,可以使用以下查询:
SELECT * FROM mytable WHERE mycolumn LIKE '%\_%' ESCAPE '\';
在上面的查询中,ESCAPE 关键字指定了转义字符为反斜杠,因此我们在通配符前添加了一个反斜杠字符。这将告诉 MySQL 仅匹配下划线字符本身,而不是作为通配符进行匹配。
SELECTstu1.s_name,tmp_t.cnt AS '同名人数' FROMstudent AS stu1LEFT JOIN (SELECT s_name, s_sex, count(*) AS cnt FROM student GROUP BY s_name, s_sex) AS tmp_t ON stu1.s_name = tmp_t.s_name AND stu1.s_sex = tmp_t.s_sex WHEREtmp_t.cnt > 1
# 1.使用模糊匹配SELECT* FROMstudent WHEREs_birth LIKE '1990%'# 2.使用正则表达式SELECT* FROMstudent WHEREs_birth REGEXP '^1990'
SELECTscore.c_id,course.c_name,round(avg(s_score), 2) AS avg_score FROMscore, coursewhere score.c_id = course.c_idGROUP BYc_idORDER BYavg_score DESC,c_id ASC
SELECTstudent.s_id,student.s_name,round(avg(s_score), 2) AS '平均成绩' FROMstudentINNER JOIN score ON student.s_id = score.s_id GROUP BYscore.s_id,student.s_id,student.s_name HAVINGavg(score.s_score) > 85
SELECTs_name,s_score FROMstudent,score WHEREstudent.s_id = score.s_id AND c_id IN (SELECT c_id FROM course WHERE c_name = '数学') AND s_score < 60
SELECTstudent.s_id,student.s_name,course.c_name,score.s_score FROMstudent,course,score WHEREstudent.s_id = score.s_id AND score.c_id = course.c_id ORDER BYs_id
SELECTstudent.s_name,course.c_name,score.s_score FROMstudent,score,course WHEREstudent.s_id = score.s_id AND score.c_id = course.c_id AND s_score > 70
SELECTstudent.s_name,course.c_name,score.s_score FROMstudent,score,course WHEREstudent.s_id = score.s_id AND score.c_id = course.c_id AND s_score < 60
SELECT student.s_id, s_name FROM student, score WHERE student.s_id = score.s_id AND c_id = '01' AND s_score >= 80
SELECTc_name,count(s_id) AS '学生人数' FROMscore,course WHEREscore.c_id = course.c_id GROUP BYscore.c_id
# 这里默认的是一门老师只教授一门课程SELECTstudent.*,score.s_score FROMstudent,score WHEREstudent.s_id = score.s_id AND c_id IN (SELECT c_id FROM course WHERE t_id IN (SELECT t_id FROM teacher WHERE t_name = '张三')) ORDER BYs_score DESC LIMIT 1
SELECTsc1.s_id,sc1.c_id,sc2.c_id,sc1.s_score,sc2.s_score FROMscore AS sc1,score AS sc2 WHEREsc1.s_id = sc2.s_id AND sc1.s_score = sc2.s_score AND sc1.c_id != sc2.c_id
SELECTsc1.c_id,sc1.s_id,count(sc2.s_score) + 1 AS rank FROMscore AS sc1LEFT JOIN score AS sc2 ON sc1.c_id = sc2.c_id AND sc1.s_score < sc2.s_score GROUP BYsc1.c_id,sc1.s_score,sc1.s_id HAVINGcount(sc2.s_score) < 2 ORDER BYsc1.c_id,rank
SELECT c_id, count(*) AS '选修人数' FROM score GROUP BY c_id HAVING count(*) > 5 ORDER BY'选修人数' DESC,c_id ASC
SELECT s_id FROM score GROUP BY s_id HAVING count(c_id) >= 2
SELECT* FROMstudent WHERE# SELECT count(*) FROM course) 查询的是总课程的数量s_id IN (SELECT s_id FROM score GROUP BY s_id HAVING count(c_id) = (SELECT count(*) FROM course))
# 1.按照年份来计算SELECTs_id,s_name,(YEAR(now()) - YEAR(s_birth)) AS age FROMstudentSELECTs_id,s_name,timestampdiff(YEAR, s_birth, now()) AS age FROMstudent
# week(时间): 默认从 0 开始,表示星期天为一个星期的第一天,国外算法# week(时间, 1): 从 1 开始,表示星期一为一个星期的第一天,国内算法SELECTs_id,s_name FROMstudent WHEREWEEK (s_birth) = WEEK (now(), 1)
SELECTs_id,s_name FROMstudent WHEREWEEK (s_birth) = WEEK (now(), 1) + 1
SELECTs_id,s_name FROMstudent WHEREMONTH (s_birth) = MONTH (now())
SELECTs_id,s_name FROMstudent WHEREMONTH (s_birth) = MONTH (now()) + 1
来源地址:https://blog.csdn.net/weixin_43004044/article/details/126557968
--结束END--
本文标题: SQL 50 题(MySQL 版,包括建库建表、插入数据等完整过程,适合复习 SQL 知识点)
本文链接: https://lsjlt.com/news/413803.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0