简体   繁体   中英

how to improve mysql query speedy with indexes?

I must run this query with MySQL:

select requests.id, requests.id_temp, categories.id
from opadithree.requests inner join
     opadi.request_detail_2
     on substring(requests.id_sub_temp, 3) = request_detail_2.id inner join 
     opadithree.categories
     on request_detail_2.theme = categories.cu_code
where categories.atc = false and id_sub_temp like "2_%";

However for some reason the query is too slow. The table requests has 15583 rows. The table request_detail_2 66469 rows and the table categories has 13452 rows.

The most problematic column id_sub_temp has data strings in the following formats: "2_number" or "3_number".

Do you know some trick to make the query faster?

Here are the indexes I'd try:

First, I need an index so your WHERE condition on id_sub_temp can find the rows needed efficiently. Then add the column id_temp so the result can select that column from the index instead of forcing it to read the row.

CREATE INDEX bk1 ON requests (id_sub_temp, id_temp);

Next I'd like the join to categories to filter by atc=false and then match the cu_code . I tried reversing the order of these columns so cu_code was first, but that resulted in an expensive index-scan instead of a lookup. Maybe that was only because I was testing with empty tables. Anyway, I don't think the column order is important in this case.

CREATE INDEX bk2 ON categories (atc, cu_code);

The join to request_detail_2 is currently by primary key, which is already pretty efficient.

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