Mysql数量上限(*)

时间:2011-12-12 17:01:21

标签: mysql optimization count limit

我有一个问题:

select count(*) from `table` where `something`>123

如果表有几百万条记录,即使列something上有索引,查询也会运行得很慢。但是,事实上我对以下的价值感兴趣:

min(100000, count(*))

那么有什么方法可以防止MySQL在已经找到100k时对行进行计数?我找到了类似的东西:

select count(*) from (select 1 from `table` where `something`>123 limit 100000) as `asd`

如果表格中包含数百万个匹配条目,则速度比count(*)快得多,但当匹配项少于100000时,count(*)的运行速度会快得多。

有没有办法更快地完成?

2 个答案:

答案 0 :(得分:1)

我没有评论的意见,所以我将此作为答案张贴......

  1. 您是否尝试过使用EXPLAIN来查看something上的索引是否真的被使用了?听起来这个查询正在进行Table Scan。理想情况下,您会希望看到类似“Extra:使用where;使用索引”。
  2. 出于好奇,something是一个可以为空的领域?
  3. 顺便说一句,也许查询优化器可以通过以下方式做得更好:

    select count(*) as cnt
    from table
    where something > 123
    having count(*) > 100000
    

答案 1 :(得分:0)

可能有助于更好地利用价值范围限制。

select count(*) - (select count(*) from t where something <= 123) as cnt
from t

另一件事可能是更新触发器计数。