当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL Server高级内容之子查询和表链接概述及使用

SQL Server高级内容之子查询和表链接概述及使用

2017年12月12日  | 移动技术网IT编程  | 我要评论

塔希恩的营地,奔跑吧兄弟第十二期完整版,ca4122

1.子查询概念
(1)就是在查询的where子句中的判断依据是另一个查询的结果,如此就构成了一个外部的查询和一个内部的查询,这个内部的查询就是自查询。
(2)自查询的分类
1)独立子查询
->独立单值(标量)子查询(=)

复制代码 代码如下:

select
testid,stuid,testbase,testbeyond,testpro
from score
where stuid=(
select stuid from student where stuname='kencery'
)

->独立多值子查询(in)
复制代码 代码如下:

select
testid,stuid,testbase,testbeyond,testpro
from score
where stuid in(
select stuid from student where stuname='kencery'
)

2)相关子查询
(3)写子查询的注意事项
1)子查询用一个圆括号阔气,有必要的时候需要为表取别名,使用“as 名字”即可。
2.表连接\
(1)表链接就是将多个表合成为一个表,但是不是向union一样做结果集的合并操作,但是表链接可以将不同的表合并,并且共享字段。
(2)表连接之交叉连接 (cross join)
1)创建两张表
复制代码 代码如下:

use test
go
create table testnum1
(
num1 int
);
create table testnum2
(
num2 int
);
insert into testnum1 values(1),(2),(3)
insert into testnum2 values(4),(5)

2) 执行交叉连接的sql语句
select * from testnum1 cross join testnum2
3)注解
交叉连接就是将第一张表中的所有数据与第二张表中的所有数据挨个匹配一次,构成一个新表。
4)自交叉的实现
执行插入sql语句:
复制代码 代码如下:

insert into testnum1 values(4),(5),(6),(7),(8),(9),(0)

执行自交叉的sql语句:
复制代码 代码如下:

select t1.num1,t2.num2 from testnum1 as t1 cross join testnum2 as t2

5)另外一种写法:
select * from testnum1,testnum2不提倡使用,首先是有比较新的语法,缺陷是逗号不明确,并且这个语法与内连接和外连接都可以使用,如果使用join声明,那么语法错误的时候可以报错,但是使用这个语法,可能因为部分语法的错误,会被sql server解释为交叉连接而跳过这个语法的检查
(3)表连接之内连接
1)内链接是在交叉连接的基础之上添加一个约束条件
2)语法:select * from 表1 inner join 表2 on 表1.字段=表2.字段
复制代码 代码如下:

selects1.stuid,
s1.stuname,
s1.stusex,
s2.testbase,
s2.testbeyond
from student as s1
inner join score as s2
on s1.stuid=s2.stuid
where s1.stuisdel=0;

(4)表连接之外连接
1)执行下面的sql语句
复制代码 代码如下:

create table tblmain
(
id int,
name nvarchar(20),
fid int
);
create table tblother
(
id int,
name nvarchar(20)
)
insert into tblmain values(1,'张三',1),(2,'李四',2)
insert into tblother values(1,'c++'),(2,'.net'),(3,'java')
select * from
tblmain as t1
inner join
tblother as t2
on
t1.fid=t2.id

2)在内连接的基础之上,在做一件事儿,就是将tblother中的java也显示出来,这时候就要使用到外连接,外连接有左外连接和右外连接。

3)左连接和右连接有什么区别呢??区别就是**连接就是以**表为主表,在内连接的基础之上,将没有数据的那张表的信息还是要显示出来供用户查看,那么这个主表就是要显示的那张表。左外连接和右外连接的分别是在前面的这张表就是左表,在后面的那张表就是右表,左连接使用left join ,有连接使用right join。
4)上面重新执行下面的sql语句,就会显示出tblother表中的java。
复制代码 代码如下:

select * from
tblmain as t1
right join tblother as t2
on t1.fid=t2.id

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网