加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

MSSQLSERVER数据库-多表查询inner join

发布时间:2020-12-12 14:25:57 所属栏目:MsSql教程 来源:网络整理
导读:好些时间都没有呆在宿舍搞C#和SQL了. 昨天因为要完成老师的作业,又开始重操旧业. 转正题,说说昨晚遇到的一个小问题,关于使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,stname nvarchar(50),sex nvarchar(2),age int,email nvarchar(50) 
) 
  
create table studentThree 
( 
    id int primary key identity(1,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','1111@qq.com'); 
insert into studentTwo(stname,email) values('未名','2','2222@qq.com'); 
  
insert into studentThree(lid,english,chinese) values(5132,'50','60'); 
insert into studentThree(lid,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?1111@qq.com
2?未名?男?2?2222@qq.com

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?1111@qq.com?1?5132?50?60
2?5100?未名?2?未名?男?2?2222@qq.com?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?1111@qq.com?男?春晓?60?50
2?5100?未名?2?2222@qq.com?男?未名?30?70


?

我的博客园原文网址:http://www.cnblogs.com/cxeye/archive/2012/05/23/2514194.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读