MySQL数据库多表联合设计模拟选课系统

版权声明:AdeCary https://blog.csdn.net/xingjidemimi/article/details/83818370
使用dtest数据库
创建学生表t4_stu
create table t4_stu(sid int auto_increment, sname varchar(64) not null, sphonum int(20) not null, primary key(sid))engine=innodb default charset=utf8;
增加学生表数据
insert into t4_stu(sname, sphonum) values('学生1', 110),('学生2', 120),('学生3', 130);
创建教师表t4_tea
create table t4_tea(tid int, tname varchar(64) not null, tphonum int(20) not null, primary key(tid))engine=innodb default charset=utf8;
增加教师表数据
insert into t4_tea(tid, tname, tphonum) values(1113, '教师1', 1111),(1114, '教师2', 1112);
创建课程表t4_course
create table t4_course(cid int auto_increment, cname varchar(64) not null,  primary key(cid))engine=innodb default charset=utf8;
增加课程表数据
insert into t4_course(cname) values('linux'),('mysql'),('hadoop');
创建选课表t4_xuanke
create table t4_xuanke(sid int, tid int, cid int,xuefen int)engine=innodb default charset=utf8;
增加选课表数据
insert into t4_xuanke(sid, tid, cid, xuefen) values(1,1113,2,2),(1,1114,1,4),(1,1113,3,6),(2,1113,2,2),(2,1114,1,2),(2,1113,3,2);
查询方法1
select s.sname, c.cname, t.tname, x.xuefen from t4_stu s, t4_tea t, t4_course c, t4_xuanke x where s.sid=x.sid and t.tid=x.tid and c.cid=x.cid;
内连接查询:
查询方法2
select s.sname, t.tname, c.cname, x.xuefen
from t4_stu s
join t4_xuanke x
	on s.sid=x.sid
join t4_tea t
	on x.tid=t.tid
join t4_course c
	on c.cid=x.cid;
查询方法3
select s.sname, t.tname, c.cname, x.xuefen
from t4_stu s
join t4_xuanke x
	using(sid)
join t4_tea t
	using(tid)
join t4_course c
	using(cid);
外连接查询:
使用外连接不但返回符合连接和查询条件的数据行,还返回不符合条件的一些行。
左连接查询
select s.sname, x.xuefen
from t4_stu s
left join t4_xuanke x
on s.sid=x.sid;
右连接查询
select s.sname, x.xuefen 
from t4_xuanke x
right join t4_stu s
on x.sid=s.sid;
左连接附加条件查询方法1
select s.sname, x.xuefen
from t4_stu s
left join t4_xuanke x
on x.sid=s.sid
	where sname='学生1';
左连接附加条件查询方法2
select s.sname,x.xuefen                       
from (select * from t4_stu where sname='学生1')
left join t4_xuanke x
on x.sid=s.sid;
①先连接后过滤
  select ……from ……
  left join ……
  on 连接条件
    where 过滤条件;
②先过滤后连接
  select ……from (select ……from ……where 过滤条件)
  left join ……
  on 连接条件;
交叉连接—笛卡尔积
  因为没有连接条件,所进行的表与表间的所有行的连接。
特点:
  ①连接查询没有写任何连接条件
  ②结果集中的总行数就是两张表中总行数的乘积(笛卡尔积)
注意:在实际中,应该要避免产生笛卡尔积的连接,特别是对于大表
mysql> select * from stu,tea,course,xuanke;
  ……
  ……
108 rows in set (0.00 sec)
若是想专门产生笛卡尔积,可以使用交叉连接
select * from t4_stu cross join t4_tea;

猜你喜欢

转载自blog.csdn.net/xingjidemimi/article/details/83818370