[英]Understanding why this MySQL outer select slows down the query
I have a Companies table and a Zipcodes table and I want to get the samllest subset of companyIDs before I apply additional processing. 我有一个COMPANY表和一个Zipcodes表,在应用其他处理之前,我想获得CompanyID的最小子集。 So often I put that in an inner select, grabbing the companyIDs on some WHERE condition and then go some aggregation or calculation (like maybe a distance calculation) on the outside.
因此,我经常将其放在内部选择中,在某些WHERE条件下获取companyID,然后在外部进行一些聚合或计算(例如,距离计算)。
For some reason I'm not understanding why this outer SELECT is slow while the inner query is blazing fast. 由于某种原因,我不理解为什么外部查询速度慢而内部查询速度快。
I know it has to do with the JOIN on the inside. 我知道这与内部的JOIN有关。 Because removing it fixes the problem.
因为删除它可以解决问题。 Somehow MySQL is deriving the tables...
SELECT _i1.companyID FROM ( SELECT companyID FROM Companies JOIN Zipcodes ON Zipcodes.zipcode = Companies.companyZipcode WHERE Companies.companyType = 'plumbing' ) _i1
Time: .8s MySQL以某种方式派生了这些表...
SELECT _i1.companyID FROM ( SELECT companyID FROM Companies JOIN Zipcodes ON Zipcodes.zipcode = Companies.companyZipcode WHERE Companies.companyType = 'plumbing' ) _i1
时间:.8s
Without the outer query: .00x seconds 不使用外部查询:.00x秒
There are indexes on Zipcodes.zipcode
and Companies.companyZipcode
and Companies.companyType
and Companies.companyID
is the Primary Key. 在
Zipcodes.zipcode
和Companies.companyZipcode
和Companies.companyType
上有索引,而Companies.companyID
是主键。
Doing an EXPLAIN shows that the outer query causes MySQL to have a select_type of Derived instead of Simple. 做一个EXPLAIN显示外部查询使MySQL的select_type为Derived而不是Simple。
当您有子查询时,需要创建一个临时表并将数据插入其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.