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
是主键。那么为什么它会遍历所有行?
答案 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;