Mysql count performance on very big tables

前端 未结 6 685
说谎
说谎 2020-11-30 00:29

I have a table with more than 100 millions rows in Innodb.

I have to know if there is more than 5000 rows where the foreign key = 1. I don\'t need the exact number.<

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 01:09

    If you're not interested to know the number of rows and you just want to test the COUNT against some value, you can use the standard script bellow:

    SELECT 'X'
    FROM mytable
    WHERE myfield='A'
    HAVING COUNT(*) >5
    

    This will return one single row or no row at all, depending if condition is met.

    This script is ANSI compliant and can be fully run without evaluating the complete value of COUNT(*). If MySQL implemented optimization to stop evaluating rows after some condition is met (I really hope it does), then you'll get a performance improvement. Unfortunately I can't test this behavior myself because I don't have a big MySQL database available. If you do this test, please share the result here :)

提交回复
热议问题