查询优化:子查询中的max()

时间:2011-06-14 16:49:15

标签: mysql performance optimization query-optimization

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

如何优化此查询? url字段是索引,id是主键。那么为什么它会遍历所有行?

2 个答案:

答案 0 :(得分:1)

MAX始终处理所有行 - 使用order by和limit - 所以查询将以这种方式查看

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

对于这种情况,不需要子查询

编辑:忘记网址

答案 1 :(得分:0)

考虑

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