为什么SQL Server对合并联接表的聚集索引列进行排序
假设我有以下表格,其中有数百万条记录:为什么SQL Server对合并联接表的聚集索引列进行排序,sql,sql-server,sorting,join,clustered-index,Sql,Sql Server,Sorting,Join,Clustered Index,假设我有以下表格,其中有数百万条记录: create table table1 ( id int not null ); alter table table1 add constraint pk_table1_id primary key ( id asc ); create table table2 ( t1_id int not null, id int not null ); alter table table2 add constraint pk_tab
create table table1 (
id int not null
);
alter table table1 add constraint pk_table1_id primary key (
id asc
);
create table table2 (
t1_id int not null,
id int not null
);
alter table table2 add constraint pk_table2_t1_id_id primary key (
t1_id asc,
id asc
);
我想这样连接这些表:
select
*
from
table1 t1
left join table2 t2
on t1.id = t2.t1_id
order by t1.id--, t2.id
SQL Server(2005)生成以下执行计划:
SQL Server正确选择合并联接操作并消除排序操作,因为两个表都已使用table1的id列进行排序
现在,如果我取消注释ORDERBY子句的第二部分,它使用表2主键的第二个键,SQL Server将使用以下计划:
即使使用合并联接提示,SQL Server也会在联接两个表后对数据进行排序
我的问题是:
- 为什么SQL Server必须对索引列的数据进行排序
- 是否有方法更改查询、表列或索引,从而使SQL Server消除此特定排序操作
orderby
排序匹配。如果是这种情况,那么自己添加“冗余”排序就更好了。测量一下看是什么。(SET STATISTICS IO ON
,SET STATISTICS TIME ON
)这个问题更有趣。它使用的是排序
,即使您使用的是ORDER BY t2.t1_id,t2.id
,这很奇怪。