Answer the question
In order to leave comments, you need to log in
How to optimize SQL query with LEFT JOIN?
There is a sqlite database and two tables
in the first (requests) all sorts of data (about 26000)
in the second (requestrewards) requestid and number (about 125000 records)
you need to select the five largest requests by the amount of requestrewards
The code below does this in more than 1 second
SELECT SUM(value) as `total`, requestid, R.*, R.rowid as id
FROM `requestrewards`
LEFT JOIN `requests` as R ON R.rowid = requestrewards.requestid
GROUP BY `requestid` ORDER BY `total` DESC LIMIT 5
Answer the question
In order to leave comments, you need to log in
Have you tried to create indexes on the columns on which you do left outer join ?
Good afternoon!
And if you try to get group 2 tables at the beginning, thereby get the sum (as I understand it, requestid is not a unique identifier). Then select top 5 from the resulting query and join from the first table.
try like this:
select total, requestid, R.*, R.rowid as id
from
(
select sum(value), requestid from requestrewards
group by requestid
order by total
) as rr
LEFT JOIN `requests` as R ON R.rowid =rr.requestid
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question