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

后端 未结 5 1577
孤城傲影
孤城傲影 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:25

    I don't know how well this works for optimization, but it should work functionally the same as exists. Exception being that it will return no row if there is no match.

    SELECT true from mytable where a = "foo" and b = "bar" LIMIT 1;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 14:44

    I have run a test with 1000 queries. SELECT EXISTS was about 25% faster than SELECT COUNT. Adding limit 1 to SELECT COUNT did not make any difference.

    0 讨论(0)
  • 2020-12-08 14:48

    Yes, MySQL (indeed all database systems as far as I'm aware) will stop processing when a row is returned when using an Exists function.

    You can read more at the MySQL documentation: If a subquery returns any rows at all, EXISTS subquery is TRUE.

    0 讨论(0)
  • 2020-12-08 14:49

    This might be an approach too.

    select 1 from mytable where a = "foo" and b = "bar" limit 1;
    

    This would not traverce all records that meet the where condition but rather return '1' after first 'hit'. The drawback is you need to check for result, because there might be empty record set in return.

    0 讨论(0)
提交回复
热议问题