简体   繁体   中英

MySQL queries very slow on join statements

So i have two tables:

| id     | make      | model        | color    |
| 1234   | BMW       | M2           | blue     |
| 2345   | Audi      | A3           | black    |

and

| id     | date       | price       | 
| 1234   | 2015-09-23 | 34000       | 
| 1234   | 2015-10-23 | 33500       | 

The first table has about 500000 unique vehicles. The second table has the price from the vehicle of everyday for a few days (will be more in the future)

Now I want to execute a simple join statement:

SELECT        count(v.id)
FROM          nm_voertuig v
JOIN          nm_voertuig_statistieken vs
ON            v.id = vs.id
WHERE         model = 'BRZ'

If I remove the join its really fast, but with the join it costs about 20 seconds to load.
I have tried to add some indexes. But it doesn't seem to help.

What am I doing wrong?

EDIT
Indexes in nm_voertuig: https://gyazo.com/cd1628862574ee3c7beb0520484819cc

EDIT 2
This is the result from EXPLAIN: https://gyazo.com/18c1ad77718e8cdf9d19a3846cc4472c

@Wouter den Ouden :

i have seen that your query use the index.

try this: first get fast the count and only join for one row and not for all.

SELECT cnt.*, vs.* FROM (
    SELECT        count(v.id), id
    FROM          nm_voertuig v
    WHERE         model = 'BRZ'
  ) AS cnt  
JOIN          nm_voertuig_statistieken vs
ON            cnt.id = vs.id;

please let me know if it works for you

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