Check if MySQL Table is empty: COUNT(*) is zero vs. LIMIT(0,1) has a result?
This is a simple question about efficiency specifically related to the MySQL implementation. I want to just check if a table is empty (and if it is empty, populate it with the default data) . Would it be best to use a statement like SELECT COUNT(*) FROM 'table'
and then compare to 0, or would it be better to do a statement like SELECT 'id' FROM 'table' LIMIT 0,1
then check if any results were returned (the result set has next)?
Although I need this for a project I am working on, I am also interested in how MySQL works with those two statements and whether the reason people seem to suggest using COUNT(*)
is because the result is cached or whether it actually goes through every row and adds to a count as it would intuitively seem to me.
It is better to do the second method or just exists
. Specifically, something like:
if exists (select id from table)
should be the fastest way to do what you want. You don't need the limit
; the SQL engine takes care of that for you.
By the way, never put identifiers (table and column names) in single quotes.
链接地址: http://www.djcxy.com/p/78572.html