When writing data to a database, it is often necessary to detect the existence of the record to be inserted before deciding whether to write.
Here I summarize the common methods for judging whether records exist:
SQL statement: SELECT COUNT (*) from TableName;
The value of Count (*) is then read to determine if the record exists. For this method of performance is a bit wasteful, we just want to determine whether records exist, there is no need to find out all.
The following method is recommended by me.
SQL statement: Select 1 from tablename where col = col Limit 1;
The number of rows affected by the execution of the statement is then read.
Of course, the limit 1 here is important. This will not be looking down after MySQL finds a record. The number of rows affected by this execution is either 0 or 1, and performance has improved a lot.
If you are using PDO, you can use ROWCOUNT () and it is easy to execute the number of rows affected.
There are also people who might read the records queried by the SQL statement, and then determine if the record exists, and then determine if the record exists. This method is feasible, but for our requirements, there is some waste, we do not need to query the records, all the performance will be lost. Not recommended here.