user198989
user198989

Reputation: 4665

MySQL is it possible to select and set at same time?

I have two queries. One selects the rows, and other one sets the row values;

mysql_query("SELECT * from messages where user='12'");

mysql_query("UPDATE messages set read='yes' where user='12'");

Is it possible to make it work using one query using if statement ? if read row is not equals to yes, update ?

Upvotes: 1

Views: 663

Answers (2)

johnny
johnny

Reputation: 19735

$result = mysql_query("SELECT * from messages where user='12'");

If (!result)
{
   //Do something
}
else
{
   mysql_query("UPDATE messages set read='yes' where user='12'");
}

Also see, how to check if mysql query return no result(record not found) using php?

EDIT: Your question is unclear as to what you are asking, but it seems to say how can you do what you want with an if statement, not do both in one query, which, if that is the case, I do not know what that question means.

EDIT: After thinking, try this,

IF EXISTS (SELECT * from messages where user='12')
THEN
UPDATE messages set read='yes' where user='12'
ELSE
SELECT * from messages where user='12'

(or do an insert)

Cue taken from,

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Upvotes: 1

jbafford
jbafford

Reputation: 5668

There might be a way to do this with stored procedures, but in general, no, retrieval and updating are distinct operations in SQL.

If what you are concerned about is making sure that only the messages you read are updated (in the case that new messages are added to the system between the select and update calls), then you will need to specify the specific message ids to update in the where clause of your update statement.

Upvotes: 1

Related Questions