MySQL資料庫多表聯合設計模擬選課系統
阿新 • • 發佈:2018-12-01
使用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;