简体   繁体   中英

mysql not using index created even after use index and force index

So I have the following query:

EXPLAIN
  SELECT
     id,
     name,
     title,
     description,
     time
  FROM entity
  WHERE 
    (date_end > CURRENT_DATE 
       OR (date_end = CURRENT_DATE AND time_end >= CURRENT_TIME)
     )
     AND (next_date < CURRENT_DATE 
        OR (next_date = CURRENT_DATE AND next_time <= CURRENT_TIME)
     )

For some reason, mysql is not using the index I created on (next_date, date_end) to handle that query.

When I do:

EXPLAIN SELECT id, name, title, description, time FROM entity WHERE (date_end = CURRENT_DATE  AND time_end >= CURRENT_TIME)

It does use the index I created on (date_end)

It seems the problem in the query is the part date_end > CURRENT_DATE and next_call < CURRENT_DATE - when those two parts are added, no indices are used.

I tried using USE INDEX and FORCE INDEX , but same result - no indices are used. i also tried ANALYZE TABLE .

My table entity is an INNODB table WITH primary key on id, and indices on date_end, next_date, and (next_date, date_end).

There is no way for MySQL to use composite index you created (next_date, date_end). Take a look at your WHERE clause:

(date_end > CURRENT_DATE OR (date_end = CURRENT_DATE AND time_end >= CURRENT_TIME)) 
AND 
(next_date < CURRENT_DATE OR (next_date = CURRENT_DATE AND next_time <= CURRENT_TIME))

there is no "part" where next_date and date_end are "composed". When you look at this WHERE part, MySql will try to "resolve" the first line, and then the second line. If you look at the first line, there are no next_date and date_end...so your composite index is useless and you cannot force mysql to use it. Creating indexes (date_end, time_end) and (next_date, next_time) would probably make sense (but not sure how much would that improve your performance.

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