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,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 studentTwo的表: id?stname?sex?age?email studentThree的表: id?lid?english?chinese ? 最后使用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 ? 可是发现表里有一些重复的字段 简单的修改一下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
我的博客园原文网址:http://www.cnblogs.com/cxeye/archive/2012/05/23/2514194.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |