In mysql determine whether the record has a method comparison

  • 2020-05-10 23:03:19
  • OfStack

Here are some common ways to determine whether a record exists:

sql statement: select count(*) from tablename;

The value of count(*) is then read to determine if the record exists. There is some waste in the performance of this method, we just want to determine whether the records exist, there is no need to check all of them.

The following method is recommended.

sql statement: select 1 from tablename where col = col limit 1;

It then reads the number of rows affected by statement execution.

Of course limit 1 is important here. It's going to take mysql to find a record and then they're not going to find it again. The number of rows affected by execution here is either 0 or 1, and the performance is much better.

If you're using PDO, you can use rowCount(), which makes it easy to see the number of rows affected by the execution.

There is also the possibility that someone might read the record that was queried by the sql statement, and then determine whether the record exists, and therefore whether the record exists. Although this method is feasible, it is still a little wasteful for our requirements. We do not need to query the records, and all the performance will be lost. Not recommended here.

Related articles: