Is EXISTS more efficient than COUNT(*)>0?

后端 未结 5 1594
孤城傲影
孤城傲影 2020-12-08 13:48

I\'m using MySQL 5.1, and I have a query that\'s roughly of the form:

select count(*) from mytable where a = \"foo\" and b = \"bar\";

In my

5条回答
  •  难免孤独
    2020-12-08 14:40

    The most reliable way is probably LIMIT 1, but that's not the point.

    Provided you have an index like CREATE INDEX mytable_index_a_b ON mytable (a,b), MySQL should be smart enough to return the count from the index and not touch any rows at all. The benefit of LIMIT 1 is probably negligible.

    If you don't have an index on (a,b), then performance will be terrible. LIMIT 1 may make it significantly less terrible, but it'll still be terrible.

提交回复
热议问题