学生---课程 多对多的关系 MYSQL带sql 可运行

在不改变原来两张表的表结构,新增加一张中间表(表1_表2),在中间表增加两个字段分别是sid和cid,将sid设置为外键,参考连接着学生表的主键,也把cid设置为外键,参考连接着课程表的主键
添加和删除数据
学生表和课程表看成主表,中间表看成从表
添加数据,先添加主表,在添加从表
删除数据,先删除从表,在删除主表
SQL

-- 创建学生表
create table student(
	sid int primary key,
	sname varchar(20)
);
-- 创建课程表
create table course(
	cid int primary key,
	cname varchar(20)
);
-- 创建中间表
create table student_course(
	sid int,
	cid int,
	-- constraint 约束  fk_sc01外键名  foreign key外键   references参考
	constraint fk_sc01 foreign key (sid) references student(sid),
	constraint fk_sc02 foreign key (cid) references course(cid)

);

-- 添加数据
insert into student values(1,'张三'),(2,'李四'),(3,'金宝'),(4,'洋老板');
insert into course values(1001,'java'),(1002,'厨师'),
(1003,'挖掘机'),(1004,'美容美发'),(1005,'盲人按摩');
insert into student_course values(1,1002),(1,1004),(2,1003),(2,1005),(3,1001),(3,1003),
(4,1001),(4,1002),(4,1003),(4,1004),(4,1005);
-- 查询金宝选择了那些课程
-- 先将三张表关联起来
select c.*,s.* from student s,student_course sc,course c
where s.sid = sc.sid and sc.cid = c.cid and s.sname = '金宝';

结果
学生---课程 多对多的关系 MYSQL带sql 可运行_第1张图片

-- 显示内连接 inner join on
select * from student s inner join student_course sc
on s.sid = sc.sid
inner join course c
on sc.cid = c.cid where s.sname = '金宝';

结果
学生---课程 多对多的关系 MYSQL带sql 可运行_第2张图片

select * from student s inner join student_course sc
inner join course c
on  s.sid=sc.sid and sc.cid = c.cid
where s.sname = '金宝';

学生---课程 多对多的关系 MYSQL带sql 可运行_第3张图片

-- 子查询  以后不用
-- 找出金宝的sid
select sid from student where sname = '金宝';

select cid from student_course where sid = (select sid from student where sname = '金宝'); 

select * from course where cid in(select cid from student_course where sid = (select sid from student where sname = '金宝'));

学生---课程 多对多的关系 MYSQL带sql 可运行_第4张图片

你可能感兴趣的:(mysql,sql,mysql,java)