現(xiàn)實生活中,我們需要查詢的數(shù)據(jù)并不獨立存在在某一張表中留晚,此時就需要進行多表聯(lián)合酵紫,進行查詢操作了。多表聯(lián)合主分四種:隱式內(nèi)連接,現(xiàn)實內(nèi)連接奖地,左外連接和右外連接橄唬。左外連接和右外連接同時使用稱為全外連接。
數(shù)據(jù)表準備(用戶鹉动,商品):
create table user(
-> id int auto_increment,
-> name varchar(30) not null,
-> gid varchar(10) default 0,
-> primary key(id)
-> );
create table goods(
-> gid int auto_increment,
-> name varchar(30) not null,
-> price int not null,
-> primary key(gid)
-> );
insert into user(neme,gid) values('GHope',3),
-> ('老子',1),
-> ('孔子',0),
-> ('鬼谷子',1),
-> ('孟子',1),
-> ('孫子',2),
-> ('莊子',2),
-> ('晏子',0);
insert into goods(name,price) values('四庫全書',200),
-> ('逍遙游',99),
-> ('時間簡史',897),
-> ('世界通史',765),
-> ('進化論',233);
隱式內(nèi)連接
查詢數(shù)據(jù)庫中誰買了哪本書
select user.neme,goods.name from user,goods where user.gid=goods.gid;
顯示內(nèi)連接
查詢數(shù)據(jù)庫中誰買了哪本書
select user.neme as uname,goods.name as gname from user join goods on user.gid=goods.gid;
左外連接
查詢用戶購買書籍情況
select user.neme as uname,goods.name as gname from user left join goods on user.gid=goods.gid;
右外連接
查看書籍被購買情況
select user.neme as uname,goods.name as gname from user right join goods on user.gid=goods.gid;
記錄聯(lián)合
查看數(shù)據(jù)庫內(nèi)所有關于用戶與書籍相關信息
select user.neme as uname,goods.name as gname from user left join goods on user.gid=goods.gid union select user.neme as uname,goods.name as gname from user right join goods on user.gid=goods.gid;
子(嵌套)查詢
查詢購買四庫全書的用戶
select neme from user where gid in (select gid from goods where name='四庫全書');