I often have to check a table column before performing an update, insert, or delete in mysql. I'm wondering if this is redundant because the mysql WHERE
clause is already a condition.
Example:
A database table named
private_messages
stores private messages for users.A column named
read
has a de开发者_如何学Pythonfault value of0
and updates to1
when a user has read a message.
Which one of the two methods is most efficient and accurate for updating the table?
Perform a query, return the value of read
, and use an if
condition:
if (read == 0) //if user did not read message
{
UPDATE private_messages
SET read = 1
WHERE id = 48 //the unique, auto increment index
}
Or simply add a WHERE AND
clause to the query:
UPDATE private_messages
SET read = 1
WHERE id = 48
AND read = 0
and use mysql_affected_rows()
to determine if a row was updated.
Edit: Another situation could be deleting a row if a column has a certain value. Should I use if
condition or where
?
I believe MySQL checks whether the new value you're trying to insert is the same as the existing value, and only performs the write operation if they are different. So no need for the IF statement.
If you alread have the read
variable in memory (ie, queried for other purposes), I would choose the first method, as if the message is not read, you won't need to query the database.
If you don't have the read
variable in memory, use the second method, has it will only query the DB one time.
The first options makes two queries to the database. The second only one. There is your answer.
The second option appears to be more efficient, because it requires only a single round-trip to the server. However, benchmarking is the only way to be sure.
You don't need either. You can simply update the row (based on id) without checking for the current value of read
. It still guarantees that after the query has been executed, the value of read
is 1.
UPDATE private_messages
SET read = 1
WHERE id = 48
1) Makes 1 or 2 db queries. 2) Always makes 2 db queries because of the mysql_affected_rows() part.
精彩评论