记录Sqlserver一个奇怪的执行计划问题
今天业务需求优化一个sql,虽然sql优化完成了,但是执行计划里的一个事让我没太弄明白。
对象:表T1和T2。
问题字段:T1和T2分别有update_time字段且都包含空。
两表关联:非主键的guid。
问题:执行 select * from t1 where update_time is null
时执行计划正常,执行 select * from t1 where update_time is null
时执行计划也正常,但是执行
selcet * from (select * from t1 where update_time is null) a join (select * from t2 where update_time is null) on a.xkey=b.xkey 时执行计划竟然多了排序,整个语句不存在order by 也没有开窗,我用mysql测试也不会出现这个问题。我这里记录一下,看看以后是否还会遇到。
具体案例:
select *from (
select * from item.ItemSnapshot where EndLocalDateTime is null ) t1 join (select * from item.ItemSnapshot where EndLocalDateTime is null) t2
on t1.ItemKey=t2.ItemKey
> ```sql |--Merge Join(Inner Join, MANY-TO-MANY
> MERGE:([Item].[ItemSnapshot].[ItemKey])=([Item].[ItemSnapshot].[ItemKey]),
> RESIDUAL:([Item].[ItemSnapshot].[ItemKey]=[Item].[ItemSnapshot].[ItemKey]))
> |--Sort(ORDER BY:([Item].[ItemSnapshot].[ItemKey] ASC))
> | |--Clustered Index Scan(OBJECT:([Item].[ItemSnapshot].[pk_ItemSnapshot]),
> WHERE:([Item].[ItemSnapshot].[EndLocalDateTime] IS
> NULL))
> |--Sort(ORDER BY:([Item].[ItemSnapshot].[ItemKey] ASC))
> |--Clustered Index Scan(OBJECT:([Item].[ItemSnapshot].[pk_ItemSnapshot]),
> WHERE:([Item].[ItemSnapshot].[EndLocalDateTime] IS
> NULL)) ```
补充:我又做了几个补充测试
1.新建同结构的表还是会排序。
2.新建表只包含关联列和过滤条件列不会排序。
3.原表只查询其中的条件列和关联列不会排序。
这问题有点头大!!