an efficient way to test if a table row exists

后端 未结 5 1634
迷失自我
迷失自我 2020-12-20 04:07

I\'m trying to find the most efficient way to determine if a table row exists.

I have in mind 3 options:

  1. SELECT EXISTS(SELECT 1 FROM table1 WHERE so

5条回答
  •  旧时难觅i
    2020-12-20 04:31

    The different methods have different pros and cons:

    SELECT EXISTS(SELECT 1 FROM table1 WHERE some_condition);
    

    might be the fastest on MySQL, but

    SELECT COUNT(1) FROM table 1 WHERE some_condition
    

    as in @Luis answer gives you the count.

    More to the point I recommend you take a look at your business logic: Very seldom is it necessary to just see if a row exists, more often you will want to

    • either use these rows, so just do the select and handle the 0-rows case
    • or you will want to change these rows, in which case just do your update and check mysql_affected_rows()
    • If you want to INSERT a row if it doesn't already exist, take a look at INSERT .. ON DUPLICATE KEY or REPLACE INTO

提交回复
热议问题