简体   繁体   中英

Optmize DISTINCT / LIMIT MySQL query for pagination

I have the following SQL:

SELECT group_id FROM products WHERE category = 12345 GROUP BY group_id LIMIT 0, 10

or:

SELECT DISTINCT group_id FROM products WHERE category = 12345 LIMIT 0, 10

The LIMIT is used for pagination. I want to know how can I avoid MySQL to lookup all rows until it finds the 10 distinct group_ids that I want. For example if I did:

SELECT DISTINCT group_id FROM products WHERE category = 12345 LIMIT 200, 10

It will scan the first 200 rows with category = 12345, than start collecting then 10 distinct group_ids?

UPDATE: What if I created an index on (group_id, category) ?

Your query will find the first 200 distinct rows, then output the next 10. The DISTINCT is done before the LIMIT . Depending on indexing and how the table is stored, it can stop collecting unique values once it fulfills the limit clause. This is most likely if the value you want distinct is indexed.

(BTW, you will improve readability of the query if you use LIMIT 10 OFFSET 200 instead of the older unintuitive LIMIT 200, 10 notation.)

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