SQL50道练习题

题目来源:https://blog.csdn.net/flycat296/article/details/63681089

1. 查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数

使用隐式

FROM student s3, (
    SELECT s1.stu_id sid,
        s1.`score` score1,
        s2.`score` score2
    
    FROM score s1, score s2

    WHERE s1.stu_id = s2.stu_id
        AND s1.`course_id` = 1
        AND s2.`course_id` = 2
        AND s1.`score` > s2.`score`) s4
WHERE s3.id = s4.sid;

显式

SELECT
    a.*,
    b.`score` score1,
    c.`score` score2
FROM
        student a
JOIN     score b
    ON a.`id`=b.`stu_id`
JOIN    score c
    ON b.course_id = 1 
    AND c.`course_id`=2 
    AND a.`id`=c.`stu_id` 
    AND b.`score`>c.`score`;
-- 题目2查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩
SELECT    s1.`id`, s1.`name`, AVG(score) average

FROM score s2
    JOIN student s1
    ON s1.`id`=s2.`stu_id`

GROUP BY s2.`stu_id`
HAVING average > 60;
-- 3. 查询在 SC 表存在成绩的学生信息
SELECT DISTINCT s1.*

FROM student s1 
RIGHT OUTER JOIN score s2 
ON s1.`id`=s2.`stu_id`;
-- 4. 查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )
SELECT 
    s1.`id`,
    s1.`name`,
    AVG(s2.`score`) average,
    COUNT(s2.`course_id`) COUNT
FROM student s1
LEFT OUTER JOIN score s2 
ON s1.`id`=s2.`stu_id`
GROUP BY s1.`id`;
-- 5.查询「李」姓老师的数量
SELECT COUNT(id) COUNT

FROM teacher t1

WHERE t1.`NAME` LIKE "李%";
-- 6. 查询学过「陈奕迅」老师授课的同学的信息
SELECT * FROM student t, score s
JOIN course c ON s.`course_id`=c.`id`
JOIN teacher t2 ON t2.`id`=c.`teacher_num`
WHERE t.`id`=s.`stu_id`
HAVING t2.`NAME`="陈奕迅";
-- 7. 查询没有学全所有课程的同学的信息
SELECT 
    s1.`id`,
    s1.`name`,
    COUNT(s2.`course_id`) COUNT

FROM score s2
    RIGHT JOIN student s1
    ON s1.`id`=s2.`stu_id`

GROUP BY s1.`id`
HAVING COUNT(s2.`course_id`) < 3;
-- 8. 查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息
SELECT DISTINCT
    s1.`id`,s1.`name`

FROM score s2
    JOIN student s1
    ON s1.`id`=s2.`stu_id`
    JOIN (    SELECT 
            *
        FROM score s2
        WHERE s2.`stu_id`=1) s3
        -- 此处返回学号01的学生选课情况
    ON s2.`course_id`=s3.`course_id`;
原文地址:https://www.cnblogs.com/try4396/p/12179567.html