简体   繁体   中英

Are these two MySQL query forms always equivalent? GROUP BY + ORDER BY + LIMIT

I ran into an optimization issue and the following change seems to serve as a workaround:

Before (100+s):

SELECT t1.*,t2.a AS t2_a,t2.b AS t2_b FROM ... JOIN ... WHERE ... GROUP BY ... ORDER BY ... LIMIT 5

After (0.01s):

SELECT * FROM
    (SELECT t1.*,t2.a AS t2_a,t2.b AS t2_b FROM ... JOIN ... WHERE ... GROUP BY ... ORDER BY ...) AS x
LIMIT 5

Setting aside the issue of whether this type of optimization is the best for my case (my research tells me it is the most practical for me to implement), are these two forms guaranteed to return the same results in all cases?

We can assume that the inner query may have many JOINs, but not other subqueries or UNIONs (ie is a simple SELECT). In my case the inner query can vary greatly depending on user input, so that's why I'm structuring this as a general question about the query forms.

The only difference is the the latter will have an additional "step" for using a derived query. Otherwise, the result will be the same.

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