首页 > 数据库技术 > 详细

sql50题

时间:2020-03-22 16:32:12      阅读:54      评论:0      收藏:0      [点我收藏+]

建表:(成绩表中的score字段应该是int类型的,在建表语句中是varchar类型的了)

技术分享图片
create table student(
    s_id varchar(10),
    s_name varchar(20),
    s_age date,
    s_sex varchar(10)
);

create table course(
    c_id varchar(10),
    c_name varchar(20),
    t_id varchar(10)
);


create table teacher (
t_id varchar(10),
t_name varchar(20)
);

create table score (
    s_id varchar(10),
    c_id varchar(10),
    score varchar(10)
);
建表Sql语句

向表中填充数据:

技术分享图片
insert into student (s_id, s_name, s_age, s_sex)
values  (01 , 赵雷 , 1990-01-01 , ),
        (02 , 钱电 , 1990-12-21 , ),
        (03 , 孙风 , 1990-05-20 , ),
        (04 , 李云 , 1990-08-06 , ),
        (05 , 周梅 , 1991-12-01 , ),
        (06 , 吴兰 , 1992-03-01 , ),
        (07 , 郑竹 , 1989-07-01 , ),
        (08 , 王菊 , 1990-01-20 , );

insert into course (c_id, c_name, t_id)
values  (01 , 语文 , 02),
        (02 , 数学 , 01),
        (03 , 英语 , 03);

insert into teacher (t_id, t_name)
values  (01 , 张三),
        (02 , 李四),
        (03 , 王五);

insert into score (s_id, c_id, score)
values  (01 , 01 , 80),
        (01 , 02 , 90),
        (01 , 03 , 99),
        (02 , 01 , 70),
        (02 , 02 , 60),
        (02 , 03 , 80),
        (03 , 01 , 80),
        (03 , 02 , 80),
        (03 , 03 , 80),
        (04 , 01 , 50),
        (04 , 02 , 30),
        (04 , 03 , 20),
        (05 , 01 , 76),
        (05 , 02 , 87),
        (06 , 01 , 31),
        (06 , 03 , 34),
        (07 , 02 , 89),
        (07 , 03 , 98);
向表中填充数据的Sql语句

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

技术分享图片
select*from(
    select d.*,c.score from
        (select a.s_id,b.score chinese from 
            (select distinct s_id from score) a
        left join score b
            on a.s_id=b.s_id
        where b.c_id=01) d
    left join score c
        on c.s_id=d.s_id
        where c.c_id=02    
    )e 
where e.chinese>e.score    
我的写法(只会使用left join)

 

技术分享图片
select a.s_id,a.score,b.score from
    (select  s_id,c_id,score from score where c_id=01)a
inner join
    (select s_id,c_id,score from score where c_id=02)b
on a.s_id=b.s_id
where a.score>b.score
好的写法

使用inner join的性能要比left join的性能要好很多!

 

2、查询平均成绩大于等于60分的同学的学生编号和平均成绩

技术分享图片
select * from(
    select s_id,avg(score) avgScore from score group by s_id)a 
where a.avgScore>60
我的写法(不会使用having条件语句)

 

技术分享图片
select s_id,avg(score) from score group by s_id having avg(score)>60
好的写法

使用having条件语句,一条sql就可以搞定了!不需要写子查询了。

 

3、查询所有学生的学号、姓名、选课数、总成绩

sql50题

原文:https://www.cnblogs.com/vichin/p/12546333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!