Best way to test if a row exists in a MySQL table

后端 未结 12 2060
小蘑菇
小蘑菇 2020-11-22 06:11

I\'m trying to find out if a row exists in a table. Using MySQL, is it better to do a query like this:

SELECT COUNT(*) AS total FROM table1 WHERE ...
         


        
相关标签:
12条回答
  • 2020-11-22 06:28

    I'd go with COUNT(1). It is faster than COUNT(*) because COUNT(*) tests to see if at least one column in that row is != NULL. You don't need that, especially because you already have a condition in place (the WHERE clause). COUNT(1) instead tests the validity of 1, which is always valid and takes a lot less time to test.

    0 讨论(0)
  • 2020-11-22 06:34

    In my research, I can find the result getting on following speed.

    select * from table where condition=value
    (1 total, Query took 0.0052 sec)
    
    select exists(select * from table where condition=value)
    (1 total, Query took 0.0008 sec)
    
    select count(*) from table where condition=value limit 1) 
    (1 total, Query took 0.0007 sec)
    
    select exists(select * from table where condition=value limit 1)
    (1 total, Query took 0.0006 sec) 
    
    0 讨论(0)
  • 2020-11-22 06:35

    I have made some researches on this subject recently. The way to implement it has to be different if the field is a TEXT field, a non unique field.

    I have made some tests with a TEXT field. Considering the fact that we have a table with 1M entries. 37 entries are equal to 'something':

    • SELECT * FROM test WHERE text LIKE '%something%' LIMIT 1 with mysql_num_rows() : 0.039061069488525s. (FASTER)
    • SELECT count(*) as count FROM test WHERE text LIKE '%something% : 16.028197050095s.
    • SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%') : 0.87045907974243s.
    • SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%' LIMIT 1) : 0.044898986816406s.

    But now, with a BIGINT PK field, only one entry is equal to '321321' :

    • SELECT * FROM test2 WHERE id ='321321' LIMIT 1 with mysql_num_rows() : 0.0089840888977051s.
    • SELECT count(*) as count FROM test2 WHERE id ='321321' : 0.00033879280090332s.
    • SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321') : 0.00023889541625977s.
    • SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321' LIMIT 1) : 0.00020313262939453s. (FASTER)
    0 讨论(0)
  • 2020-11-22 06:35

    Suggest you not to use Count because count always makes extra loads for db use SELECT 1 and it returns 1 if your record right there otherwise it returns null and you can handle it.

    0 讨论(0)
  • 2020-11-22 06:35

    At times it is quite handy to get the auto increment primary key (id) of the row if it exists and 0 if it doesn't.

    Here's how this can be done in a single query:

    SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...
    
    0 讨论(0)
  • 2020-11-22 06:37

    COUNT(*) are optimized in MySQL, so the former query is likely to be faster, generally speaking.

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