[英]Query optimization: max() in subquery
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
是主键。 那么为什么它会遍历所有行呢?
MAX 总是处理所有行 - 使用 order by 和 limit - 所以查询看起来像这样
SELECT * FROM wbsites WHERE url = '...' ORDER BY id DESC LIMIT 1
对于这种情况,不需要子查询
编辑:忘记 url 在哪里
考虑
alter table websites add index a (url, active);
select active
from websites
where url = 'google.com'
order by id desc
limit 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.