MSSQLSERVER数据库-多表查询inner join

好些时间都没有呆在宿舍搞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

发布了40 篇原创文章 · 获赞 4 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章