联接查询中的表顺序

Jua*_*lez 7 join sql-server

如果我说:

Table1 left join Table2
Run Code Online (Sandbox Code Playgroud)

和说一样吗?:

Table2 right join Table1
Run Code Online (Sandbox Code Playgroud)

换句话说,我是否应该期望从 2 个相同的查询中获得相同的结果,其中唯一改变的是首先写入哪个表以及是使用左连接还是右连接(遵循我上面描述的相同模式?)

Tho*_*ger 8

是的,结果是一样的。以这个为例:

if exists(select * from sys.tables where name = 'T1')
    drop table T1
go
if exists(select * from sys.tables where name = 'T2')
    drop table T2
go

create table T1
(
    id int not null,
    someText varchar(100) not null
)
go

insert into T1
values(1, 'hello'),
(3, 'bye'),
(6, 'what')
go

create table T2
(
    id int not null,
    someText varchar (100) not null
)
go

insert into T2
values(2, 'hi'),
(3, 'ciao'),
(4, 'no')
go

select *
from T1
left join T2
on T1.id = T2.id

select *
from T2
right join T1
on T2.id = T1.id
Run Code Online (Sandbox Code Playgroud)

输出将具有相同的精确字段(请注意,如果您使用SELECT *列顺序将在查询之间不同)具有相同的精确数据。

作为参考,这里有两个执行计划:

在此处输入图片说明