简体   繁体   中英

MySQL - Combining DISTINCT, ORDER BY and LIMIT

I'm wondering what should be expected from an SQL query that involves the operators DISTINCT , ORDER BY and LIMIT . I think my question is rooted in a misunderstanding of the order in which operators in SQL should be applied

For instance,

CREATE TABLE test(id int)

SELECT DISTINCT id
FROM test
ORDER BY id
LIMIT 10

Based on my knowledge of SQL, I can't see which (if any) of the following should happen

  1. The first 10 rows of test are sorted, then a list of distinct id s in that subset are returned
  2. A list of all the distinct id s in test are sorted, then the top 10 are returned
  3. A list of the distinct id 's in the first 10 rows of test are sorted then returned

If it matters, I'm using MySQL (MyISAM)

Think of it in terms of "inside to out", so the following happens:

  1. Get a list of distinct ids
  2. Order them in ascending order
  3. List the first 10

SELECT first, then ORDER BY, then LIMIT. That's true except for a few databases (well, I know one) that has both the TOP and LIMIT keywords. In that engine, LIMIT is part of the WHERE clause (evaluated at the SELECT level) and TOP is applied after ORDERing.

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