Query optimization: max() in subquery

萝らか妹 提交于 2019-12-11 05:05:19

问题


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;


来源:https://stackoverflow.com/questions/6347096/query-optimization-max-in-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!