I want to query whether an id exists in a mysql table? Which of the following two methods is more efficient? Method 1: {code...} Method 2: {code...} or is there a more efficient way? I want to query whether an id exists in a mysql table? Which of the following two methods is more efficient?
Method 1:
$ SQL = "select count (*) FROM 'table' WHERE id = 10"; $ rst = mysql_query ($ SQL); $ row = mysql_fetch_row ($ rst ); if ($ row [0]) {// you can use $ row [0] to determine whether id = 10 exists}
Method 2:
$ SQL = "SELECT * FROM 'table' WHERE id = 10"; $ rst = mysql_query ($ SQL); $ arr = mysql_fetch_assoc ($ rst); if ($ arr) {// determine whether id = 10 exists by array $ arr}
Or is there a more efficient way?
Reply content:
I want to query whether an id exists in a mysql table? Which of the following two methods is more efficient?
Method 1:
$ SQL = "select count (*) FROM 'table' WHERE id = 10"; $ rst = mysql_query ($ SQL); $ row = mysql_fetch_row ($ rst ); if ($ row [0]) {// you can use $ row [0] to determine whether id = 10 exists}
Method 2:
$ SQL = "SELECT * FROM 'table' WHERE id = 10"; $ rst = mysql_query ($ SQL); $ arr = mysql_fetch_assoc ($ rst); if ($ arr) {// determine whether id = 10 exists by array $ arr}
Or is there a more efficient way?
I think
select id from `table` where id=10 limit 1
It is more efficient. It will not continue when one item is hit.
SELECT id FROMtableWHERE id = 10
Which of the following statements do you want to perform the count operation?
It is better to write select 1 from table where id = 10 limit 1. In fact, I remember that these are similar,
If the id is indexed, do not select non-index fields. In this way, you only need to go to the index file for the query.
No longer
Do not selectGenerally, all IDs are indexed. select ID is fine. SQL statement. If there is more data, select ID and selectThe efficiency is still quite high. You can use worms to copy and generate millions of data records for comparison.
According to my previous impressions, it's faster than COUNT.
Try not to use functions in SQL...