好些時間都沒有呆在宿舍搞C#和SQL了. 昨天因爲要完成老師的作業, 又開始重操舊業.
轉正題, 說說昨晚遇到的一個小問題, 關於使inner join來進行多表查詢.
對於沒有從事過真正項目開發維護的人,或者對於大多數的學生,都很少需要自己在做汲及到數據庫方面的程序時使用到inner join吧!?
因爲自己搞的話 很多時候表的哪些字段自己已經寫好了.
但問題出現了, 如果有一天創建的表不是你. 你要使用別人創建的表, 但是別人創建的這張表沒有你需要的數據庫字段.
這時候你需要在原有的表上根據裏面的某個主鍵再創建一張附加的表
進行查詢時 希望兩張表合在一起 這時候就要用到inner join.
使用inner join很簡單, 但我遇到的這麼一個小問題是, 我要三張甚到四張表的inner join 而不是兩張表的inner join 該怎麼寫?
就是這個小問題!
把過程記錄下來一下
create table studentOne
(
id int primary key identity(1,1),
lid int,
stname nvarchar(50)
)
create table studentTwo
(
id int primary key identity(1,1),
stname nvarchar(50),
sex nvarchar(2),
age int,
email nvarchar(50)
)
create table studentThree
(
id int primary key identity(1,1),
lid int,
english nvarchar(50),
chinese nvarchar(50)
)
創建了三張表後, 插入數據:
insert into studentOne(lid,stname) values(5132,'春曉')
insert into studentOne(lid,stname) values(5100,'未名')
insert into studentTwo(stname,sex,age,email) values('春曉','男','1','[email protected]');
insert into studentTwo(stname,sex,age,email) values('未名','男','2','[email protected]');
insert into studentThree(lid,english,chinese) values(5132,'50','60');
insert into studentThree(lid,english,chinese) values(5100,'70','30');
查看一下 三張表分別的顯示
select * from studentOne;
select * from studentTwo;
select * from studentThree;
studentOne的表:
id lid stname
1 5132 春曉
2 5100 未名
studentTwo的表:
id stname sex age email
1 春曉 男 1 [email protected]
2 未名 男 2 [email protected]
studentThree的表:
id lid english chinese
1 5132 50 60
2 5100 70 30
最後使用inner join來查詢下
select * from studentOne
inner join studentTwo on studentOne.stname = studentTwo.stname
inner join studentThree on studentOne.lid = studentThree.lid
id lid stname id stname sex age email id lid english chinese
1 5132 春曉 1 春曉 男 1 [email protected] 1 5132 50 60
2 5100 未名 2 未名 男 2 [email protected] 2 5100 70 30
可是發現表裏有一些重複的字段 簡單的修改一下SQL語句
select studentOne.id,studentOne.lid,studentOne.stname,studentTwo.age,studentTwo.email,
studentTwo.sex,studentTwo.stname,studentThree.chinese,studentThree.english
from studentOne
inner join studentTwo on studentOne.stname = studentTwo.stname
inner join studentThree on studentOne.lid = studentThree.lid
最後顯示結果如下:
id lid stname age email sex stname chinese english
1 5132 春曉 1 [email protected] 男 春曉 60 50
2 5100 未名 2 [email protected] 男 未名 30 70
我的博客園原文網址:http://www.cnblogs.com/cxeye/archive/2012/05/23/2514194.html