Query optimization: max() in subquery

2019-08-04 16:44发布

问题:

select active from websites where id = (select max(id) from websites where url = 'google.com')

id  select_type table     type   possible_keys  key      key_len  ref    rows  Extra
1   PRIMARY     websites  const  PRIMARY        PRIMARY  4        const  1   
2   SUBQUERY    websites  ref    url            url      767             1867  Using where

How can I optimize this query? The url field is index and id is the primary key. So why is it going through all the rows?

回答1:

MAX always process all rows - use order by and limit - so query will look this way

 SELECT * FROM wbsites WHERE url = '...' ORDER BY id DESC LIMIT 1

For this case subquery is not required

EDIT: Forgot where url



回答2:

Consider

alter table websites add index a (url, active);
select active 
    from websites 
    where url = 'google.com' 
    order by id desc 
    limit 1;