1

Here's the format of mysql code

select a,b,c 
from table1 
left join table2 on x=y 
left join table3 on m=n
limit 100000, 10

I know know to optimize limit when I have a large offset. But I couldn't find the solution to optimize the one with multiple tables, is there any way to make my query faster?

1
  • Do you need "LEFT"? Commented Jun 4, 2021 at 22:43

1 Answer 1

1

First of all, offsets and limits are unpredictable unless you include ORDER BY clauses in your query. Without ORDER BY, your SQL server is allowed to return result rows in any order it chooses.

Second, Large offsets and small limits are a notorious query-performance antipattern. There's not much you can to do make the problem go away.

To get decent performance, it's helpful to rethink why you want to use this kind of access pattern, and then try to use WHERE filters on some indexed column value.

For example, let's say you're doing this kind of thing.

select a.user_id, b.user_email, c.user_account
from table1 a
left join table2 b on a.user_id = b.user_id 
left join table3 c on b.account_id = c.account_id
limit whatever

Let's say you're paginating the query so you get fifty users at a time. Then you can start with a last_seen_user_id variable in your program, initialized to -1.

Your query looks like this:

select a.user_id, b.user_email, c.user_account
from (
        select user_id 
          from table1 
         where user_id > ?last_seen_user_id?
         order by user_id
         limit 50
     ) u
join      table1 a on u.user_id = a.user_id
left join table2 b on a.user_id = b.user_id 
left join table3 c on b.account_id = c.account_id
order by a.user_id

Then, when you retrieve that result, set your last_seen_user_id to the value from the last row in the result.

Run the query again to get the next fifty users. If table1.user_id is a primary key or a unique index, this will be fast.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer, this solution may be the optimize solution for me. I was initially thinking about to create a new table to have an index, but it costs so much space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.