简体   繁体   中英

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

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...

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.

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.

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

The only plausible explanation is caching. Not just MySQL caching, but also OS level caching like disk cache. Even if you use the SQL_NO_CACHE cache directive, that just means MySQL won't cache that query result. MySQL will still cache the index and table through normal caching methods.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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