sql server 各种查询语句详解left jion,right join,full join ,join,inner join ,union all,union等

建库建表

create database testDataBase

create table TStudent
(
	Stuid   int identity (1,1) PRIMARY KEY,
	StuName varchar(50),
	StuClass int FOREIGN KEY REFERENCES TClass(ClassId)
)

create table TClass
(
	ClassId  int identity (100,1) PRIMARY KEY,
	ClassName varchar(50)
)


create table teacher
(
	tid  int identity (10,1) PRIMARY KEY,
	tname varchar(50),
	tage int ,
	CountryName varchar(50) FOREIGN KEY REFERENCES Country(cname)
)

create table Country
(
	Stuname varchar(50) ,
	cname varchar(50) primary key
)

–内连接相关知识
–1.等值连接
–1.1 概念:在连接条件中使用等于号(=)运算符,其查询结果中列出被连接表中的所有列,包括其中的重复列。

select * from  TStudent ts,TClass tc where ts.StuClass = tc.ClassId 

–这条语句可以采用inner join
–等于

select * from TStudent ts inner join TClass tc on ts.StuClass = tc.ClassId 

–2.不等连接
–2.1概念:在连接条件中使用除等于号之外运算符(>、<、<>、>=、<=、!>和!<)
– 各类>、<、<>、>=、<=、!>和!< 都可以试试看

select * from TStudent ts inner join TClass tc on ts.StuClass !> tc.ClassId

–外连接相关知识
–1.左连接 left join
–1.1 概念:返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值。

select * from TStudent ts left join TClass tc on ts.StuClass = tc.ClassId

–1.2总结:左连接显示左表全部行,和右表与左表相同行。

–2.右连接 right join
–2.1 恰与左连接相反,返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。

select * from TStudent ts right join TClass tc on ts.StuClass = tc.ClassId

–2.2总结:右连接恰与左连接相反,显示右表全部行,和左表与右表相同行。

–3.全连接 full join
–3.1概念:返回左表和右表中的所有行。当某行在另一表中没有匹配行,则另一表中的列返回空值

select * from TStudent ts  full join TClass tc on ts.StuClass = tc.ClassId

–3.2总结:返回左表和右表中的所有行。

–4.交叉连接( 笛卡尔积) CROSS JOIN
–4.1 概念:不带WHERE条件子句,它将会返回被连接的两个表的笛卡尔积,返回结果的行数等于两个表行数的乘积
–(例如:TStudent和TClass,返回4*4=16条记录),如果带where,返回或显示的是匹配的行数。
–不带where 条件写法

select * from TStudent  cross join TClass

–也等于

select * from TStudent , TClass

–4.2有where子句,往往会先生成两个表行数乘积的数据表,然后才根据where条件从中选择。

select * from TStudent ts cross join TClass tc where ts.StuClass = tc.ClassId   

–(注:cross join后加条件只能用where,不能用on)

–5 联合查询 union , union all
–5.1 找到所有的班级编号:

select StuClass from TStudent
union 
select ClassId from TClass 

–5.2
–Union all这个指令的目的也是将两个SQL语句的结果合并起来,不过它与union的不同之处在
–Union all会将所有的结果都列出来,包括重复的结果,这是它与union的不同之处。
–union all规则
–就是把2个具有相同列及数据类型的 结果 放到一起显示,并且不去重。
–select a,b,c from table1 union all select ca,cb,cc from table2

select a,b,c from table1  union all select ca,cb,cc from table2
select StuClass from TStudent
union  all
select ClassId from TClass 

–6.intersect用法和minus用法:
–6.1 intersect用法

select tname as '相同名' from teacher  intersect select Stuname from Country

–6.2 minus用法
–Minus指令是运用在两个SQL语句上,它先找出第一个SQL语句所产生的结果,然后看这些结果
–有没有在第二个sql语句的结果中,如果有的话就去除。还有一点就是如果第二个sql语句所产生
–的结果没有在第一个sql语句所产生的结果内,那么这个数据也去除。

select * from teacher
select tname  from teacher  
minus   
select Stuname from Country
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值