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

后端 未结 12 2064
小蘑菇
小蘑菇 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:47

    I feel it is worth pointing out, although it was touched on in the comments, that in this situation:

    SELECT 1 FROM my_table WHERE *indexed_condition* LIMIT 1
    

    Is superior to:

    SELECT * FROM my_table WHERE *indexed_condition* LIMIT 1
    

    This is because the first query can be satisfied by the index, whereas the second requires a row look up (unless possibly all the table's columns are in the index used).

    Adding the LIMIT clause allows the engine to stop after finding any row.

    The first query should be comparable to:

    SELECT EXISTS(SELECT * FROM my_table WHERE *indexed_condition*)
    

    Which sends the same signals to the engine (1/* makes no difference here), but I'd still write the 1 to reinforce the habit when using EXISTS:

    SELECT EXISTS(SELECT 1 FROM my_table WHERE *indexed_condition*)
    

    It may make sense to add the EXISTS wrapping if you require an explicit return when no rows match.

提交回复
热议问题