简体   繁体   中英

MySql Query runs too slow after adding order by

I'have an issue with a MySql Query

Two tables.
Persons tabel (25000 records)
persid (Primary key)
voornaam
tussenvoegsel
achternaam (index)

Line Ups tabel (370000 records)
Opstelkey (Primary key)
wid
Persid
volgorde
gesp
gesc

SELECT sum(o.gesc) as totgescoord,p.achternaam 
FROM opstelere1 o,personen1 p
where o.persid=p.persid
group by o.persid

Result above Query 6809 totaal, Query duration 0,0176 seconds

Adding Order By, the Query runs a lot slower.

SELECT sum(o.gesc) as totgescoord,p.achternaam 
FROM opstelere1 o,personen1 p
where o.persid=p.persid
group by o.persid
order by totgescoord desc

Result this Query 6809 totaal, Query duratiob 2,7740 seconds

Query only on Line Ups Table with use of persid

SELECT o.persid,sum(o.gesc) as totgescoord 
FROM opstelere1 o
group by o.persid
order by totgescoord desc 

Resultaat Query 6809 totaal, Query duration 0,1732 seconds But it's nice to see a name instead of a persid;-)

Turn the query inside-out. This way it can start with the GROUP BY . This lets it shrink 370000 rows into 6809 before touching the other table. Then there are only 6809 lookups in that other table, not 370000.

SELECT  o2.totgescoord,
        p.achternaam 
    FROM ( SELECT persid, SUM(gesc) AS totgescoord
               FROM opstelere1
               GROUP BY persid ) AS o2
    JOIN personen1 AS p  ON p.persid = o2.persid
    ORDER BY o2,totgescoord DESC;

Also, opstelere1 needs INDEX(persid, gesc) (in this order).

Your query is and example of explode-implode.

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