大数据学习第九天(mysql查询已选/没选的课程)

本文详细描述了如何在MySQL中创建表并插入数据,以及执行两个SQL查询来分别查找已选和未选的课程。
摘要由CSDN通过智能技术生成

1、创建表和添加数据

create database day1 charset utf8;
use day1;
create table student
(
    id   int unsigned primary key auto_increment not null,
    name varchar(20)                             not null comment '学生姓名'
);
insert into student
values (0, '张三'),
       (0, '李四'),
       (0, '王五'),
       (0, '赵六'),
       (0, '田七');
create table course
(
    id   int unsigned primary key auto_increment not null,
    name varchar(20)                             not null comment '课程名称'
);
insert into course
values (0, '语文'),
       (0, '数学'),
       (0, '英语'),
       (0, '物理'),
       (0, '化学'),
       (0, '历史'),
       (0, '地理');
create table stu_cour
(
    stu_id  int comment '学生id',
    cour_id int comment '课程id',
    primary key (stu_id, cour_id)
);

insert into stu_cour
values (1, 1),
       (1, 2),
       (1, 3),
       (1, 4),
       (2, 1),
       (2, 2),
       (2, 3),
       (2, 5),
       (3, 1),
       (3, 2),
       (3, 3),
       (3, 7),
       (4, 1),
       (4, 2),
       (4, 3),
       (4, 4),
       (5, 1),
       (5, 2),
       (5, 3),
       (5, 5);

2、表的样子

course表

stu_cour表

student表

3、题目

1)查询已经被选过的课程有哪些

select distinct a.name
from course a
         left join stu_cour b on a.id = b.cour_id
where b.cour_id in (select id from course);

2)查询还没有被选过的课程有哪些

select name
from course
where course.name not in (select distinct a.name
                          from course a
                                   left join stu_cour b on a.id = b.cour_id
                          where b.cour_id in (select id from course));
select * from course;

这两个查询折磨了半个小时,必须把这俩晒一晒

  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值