简体   繁体   中英

Slow MySQL distinct with where

I have a large table that has two columns (among others):

  • event_date
  • country

This query is very fast:

select distinct event-date from my_table

This query is also very fast:

select * from my_table where country = 'US'

However, this query is very slow:

select distinct event_date from my_table where country = 'US'

I tried adding all combinations of indexes, including one on both columns. Nothing makes the third query faster.

Any insights?

Have you tried staging the results in a temporary table, adding an index, then completing the query from there? Not sure if this will work in MySQL, but it's a trick I use successfully in MSSQL quite often.

CREATE TEMPORARY TABLE IF NOT EXISTS staging AS (
    SELECT event_date FROM my_table WHERE country = 'US'
);
CREATE INDEX ix_date ON staging(event_date);
SELECT DISTINCT event_date FROM staging;
ALTER TABLE my_table ADD INDEX my_idx (event_date, country);

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