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

后端 未结 12 2059
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:39

    A short example of @ChrisThompson's answer

    Example:

    mysql> SELECT * FROM table_1;
    +----+--------+
    | id | col1   |
    +----+--------+
    |  1 | foo    |
    |  2 | bar    |
    |  3 | foobar |
    +----+--------+
    3 rows in set (0.00 sec)
    
    mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1);
    +--------------------------------------------+
    | EXISTS(SELECT 1 FROM table_1 WHERE id = 1) |
    +--------------------------------------------+
    |                                          1 |
    +--------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 9);
    +--------------------------------------------+
    | EXISTS(SELECT 1 FROM table_1 WHERE id = 9) |
    +--------------------------------------------+
    |                                          0 |
    +--------------------------------------------+
    1 row in set (0.00 sec)
    

    Using an alias:

    mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1) AS mycheck;
    +---------+
    | mycheck |
    +---------+
    |       1 |
    +---------+
    1 row in set (0.00 sec)
    

提交回复
热议问题