Reputation: 1523
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:
Upvotes: 1
Views: 77
Reputation: 1269445
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);
Upvotes: 2