简体   繁体   中英

MySQL queries very slow

So I have a very big database that keeps getting bigger everyday. But I don't really understand how I can use it faster. I also don't know how indexes work.

This are the tables in my database:
First table is a table with all vehicle information:

nm_voertuig:

+----+----------+------+--------+--------+-------+
| id | kenteken | merk | model  | deuren | kleur |
+----+----------+------+--------+--------+-------+
|  1 | 12KT43   | Opel | ZAFIRA |      5 | Blue  |
|  2 | G345CP   | Audi | A3     |      3 | Black |
+----+----------+------+--------+--------+-------+


在此处输入图片说明
In this table are like 500000 rows.


nm_voertuig_statistieken:

+----+------------+----------+-------+---------+
| id |   datum    | kenteken | prijs | kmstand |
+----+------------+----------+-------+---------+
|  1 | 2016-01-05 | 12KT43   |  5000 |  150000 |
|  1 | 2016-01-06 | 12KT43   |  4900 |  150000 |
|  2 | 2016-01-05 | G345CP   | 12000 |  100000 |
+----+------------+----------+-------+---------+


在此处输入图片说明
Everyday the database will be filled with the price of that day. So as long as the car is still available it wil get a new row every day.

So for example I want to get the minimum and maximum mileage of an Opel Zafira. This is the query I tried:

SELECT      MIN(kmstand), MAX(kmstand)
FROM        (
                SELECT v.id
                FROM nm_voertuig v
                WHERE merk = 'Opel' AND model = 'ZAFIRA'
            ) AS cnt
JOIN nm_voertuig_statistieken vs
ON cnt.id = vs.id

It takes very long to execute this query: 在此处输入图片说明

What can I do to make the queries faster?

EDIT:
Explain select * from nm_voertuig:
在此处输入图片说明

Explain select * from nm_voertuig_statistieken:
在此处输入图片说明

First, you should rewrite the query. Subqueries in MySQL incur overhead for materialization. So:

SELECT MIN(vs.mileage), MAX(vs.mileage)
FROM nm_voertuig v JOIN
     nm_voertuig_statistieken vs
     ON v.id = vs.id
WHERE v.make = 'Opel' AND v.model = 'ZAFIRA';

Then, for this index, you want the following indexes:

CREATE INDEX idx_nm_voertuig_make_model_id
    ON nm_voertuig(make, model, id);

CREATE INDEX idx_nm_voertuig_statistieken_id_milage
    ON nm_voertuig_statistieken(id, mileage);

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