问题描述
程序有A和B两个表数据量都在40万左右,现在需要关联两个表进行查询。但是发现一个奇怪的现象,Sql语句在添加order by排序后执行查询需要花费40秒左右,如果删除排序只花费0.1秒就可以完成查询。
Sql语句结构如下:
select distinct
A.typeNum,A.typeName,A.typeTime
from (
select distinct typeNum,typeName,typeTime from A
)A left join(
select distinct typeNum from B
)B on A.typeNum=B.typeNum
where
B.typeNum is not null
order by typeTime desc,typeName
在花费一些时间后我对Sql语句进行了调整,修改后的语句添加排序后也只消耗0.1秒。
select
*
from (
select distinct
A.typeNum,A.typeName,A.typeTime
from A left join(
select distinct typeNum from B
)B on A.typeNum=B.typeNum
where
B.typeNum is not null
)tem
order by typeTime desc,typeName
期望
虽然问题解决了,但是我搞不明白其中的原理,希望能有大神能够指点一下问题产生的原因,以及相关的数据库机制。
万分感谢帮助!!!