J
J
Jonh Doe2013-12-08 22:24:14
Search Engine Optimization
Jonh Doe, 2013-12-08 22:24:14

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

I really want to optimize, because real data is needed. Cash won't work.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
Geckelberryfinn, 2013-12-20
@CodeByZen

Have you tried to create indexes on the columns on which you do left outer join ?

P
PCHELA_MATKA, 2013-12-08
@PCHELA_MATKA

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.

S
svd71_1, 2013-12-08
@svd71_1

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

although the problem is in R.*. Are you sure you need all the fields from that table?

J
Jonh Doe, 2013-12-09
@CodeByZen

While solved a problem the trigger on record. But this is not a solution but a crutch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question