简体   繁体   English

MySQL作为子查询运行查询的速度比普通查询快

[英]MySQL running a query faster as a Subquery than plain

Can anyone tell me why this subquery method is faster than a plain query? 谁能告诉我为什么这个子查询方法比普通查询更快? As far as I can tell they're identical in theory :S 据我所知,它们在理论上是相同的:S

SELECT
    temp.`[thing]`,
FROM ( SELECT 
    `[thing]`
FROM 
    `[table]`  
WHERE 
    [things] ) temp

is faster than: 快于:

SELECT 
    `[thing]`
FROM 
    `[table]`  
WHERE 
    `[things]`

The one in the subquery is over 5x faster... 子查询中的一个要快5倍以上...

Can anyone tell me what in my config could cause such an issue? 谁能告诉我在我的配置中什么会引起这种问题?

Cheers. 干杯。

Considering quite a number of people didn't get the question I'll rephrase. 考虑到很多人没有得到我重新表述的问题。 The queries do the same thing. 查询执行相同的操作。 They are the same but in one the result is referenced from a outerquery the other is just plain. 它们是相同的,但其中一个是从外部查询引用的结果,另一个只是普通的。

SELECT `name` FROM `members` WHERE `member_id` = 1

or 要么

SELECT tmp.`name` FROM ( SELECT `name` FROM `members` WHERE `member_id` = 1 ) tmp

Lets say member_id is the primary key and is the only index of members. 可以说member_id是主键,并且是成员的唯一索引。

Any other info you want to know about this odd issue just ask in a comment and I'll provide. 您想知道有关此奇怪问题的任何其他信息,只需在评论中提出,我就会提供。 Without just giving you a dump of my whole setup I don't know what is causing this issue hence the lack of general information and the question is "what in my setup could cause this". 不仅仅给您整个安装过程的信息,我不知道是什么导致了此问题,因此缺少一般信息,问题是“安装过程中可能导致此问题的原因”。

Do it yourself, run a generic SELECT statement then run it again with itself in a subquery and see if it is faster on your system. 自己做,运行一个通用的SELECT语句,然后在子查询中再次运行它,看看它在您的系统上是否更快。

Edit: accepted answer isn't really the answer but it is the only answer I've been given so I'll close the question. 编辑:接受的答案并不是真正的答案,但这是我得到的唯一答案,因此我将结束问题。

Is it a typo or are you pre-filtering the table in the subselect? 是错字还是在子选择中预先过滤了表格?

[things] vs. [thing] in the WHERE statements WHERE语句中的[things][thing]

The only plausible explanation is caching. 唯一合理的解释是缓存。 Not just MySQL caching, but also OS level caching like disk cache. 不仅是MySQL缓存,还有像磁盘缓存一样的OS级缓存。 Even if you use the SQL_NO_CACHE cache directive, that just means MySQL won't cache that query result. 即使您使用SQL_NO_CACHE缓存指令,也仅表示MySQL不会缓存该查询结果。 MySQL will still cache the index and table through normal caching methods. MySQL仍将通过普通的缓存方法来缓存索引和表。

You would really need to make sure you cache in clear, then reverse your queries, running the sub-select first. 您确实需要确保清除缓存,然后反向查询,首先运行子选择。 Then see if you get the same result. 然后查看是否得到相同的结果。 Also, you should run them both multiple times. 此外,您应该多次运行它们。 It's very likely that you'll see that only first query is "slow". 您很可能会看到只有第一个查询是“缓慢的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM