简体   繁体   中英

Mysql query - faster?

So I have this MySQL query, and as I have lots of records this gets very slow, the computers that use the software (cash registers) aren't that powerful either. Is there a way to get the same result, but faster? Would really appreciate help!

SELECT d.sifra, COUNT(d.sifra) AS pogosti, c.*, s.Stevilka as Stev_sk FROM Cenik c, dnevna d, Podskupina s 
WHERE d.sifra = c.Sifra AND d.datum >= DATE(DATE_SUB(NOW(),INTERVAL 3 DAY))
GROUP BY d.sifra ORDER BY pogosti DESC limit 27

Have you tried indexing ?

You are using c.Sifra in the WHERE, so you probably want

CREATE INDEX Cenik_Sifra ON Cenik(Sifra);

Also you use datum and sifra from dnevna, and datum is your SELECT, so

CREATE INDEX dnevna_ndx ON dnevna(datum, sifra);

Finally there's no JOIN condition on Podskupina, whence you draw Stevilka. Is this a constant table? As it is, you're just counting rows in Podskupina and/or getting an unspecified value out of it, unless it only has the one row.

On some versions of MySQL you might also find benefit in pre-calculating the datum:

SELECT @datum := DATE(DATE_SUB(NOW(), INTERVAL 3 DAY))

and then use @datum in your query. This might improve its chances of a good indexed performance.

Without knowing more about the structure and cardinality of the involved tables, though, there's little that can be done.

At the very least you should post the result of

EXPLAIN SELECT...(your select)

in the question.

你没有加入 Podskupina s 的条件,并且你得到了交叉联接(全部对所有),所以你从 join "d.sifra = c.Sifra" 得到 x 行乘以 Podskupina s 的 y 行

This looks like a very problematic query. Do you really need to return all of c.* ? And where's the join or filter on Podskupina? Once you tighten the query, make sure you've created good indexes on the tables. For example, presuming you've already got a clustered index on a unique ID as a primary key in dnevna, performance would typically benefit by putting a secondary index on the sifra and datum columns.

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