Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Updated Value in MySQL instead of affected rows

Tags:

I've been trying to find an answer to this question, but haven't found any definitive "yes" or "no" in all my research.

I'm running a simple MySQL query like this:

 UPDATE item SET `score`=`score`+1 WHERE `id`=1 

Is there a way for that query to return the updated value, instead of the number of rows affected? Just as a reference, I'm doing this in PHP, so the actual code looks like:

 $sql = "UPDATE item SET `score`=`score`+1 WHERE `id`=1";  $new_value = mysql_query($sql);   //Unfortunately this does not return the new value 

I know I could do a second query and just SELECT the value, but I'm trying to cut down on queries as much as possible. Is there a way?

like image 262
jwegner Avatar asked Sep 16 '11 14:09

jwegner


People also ask

How check row is affected in MySQL?

mysql_affected_rows() may be called immediately after executing a statement with mysql_real_query() or mysql_query() . It returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE , DELETE , or INSERT . For SELECT statements, mysql_affected_rows() works like mysql_num_rows() .

What is Row_count () in MySQL?

In MySQL the ROW_COUNT() function is used to return the number of rows affected by the previous SQL statement. If the previous statement was not one that could potentially change data rows or you can say, it wasn't an INSERT, UPDATE, DELETE or other such statement this function will return -1.

What is Sql_calc_found_rows in MySQL?

MySQL has a nonstandard query modifier called SQL_CALC_FOUND_ROWS. When in use on a SELECT with LIMIT, it attempts to calculate how many rows would have been returned if the limit were not there, and then store that for later retrieval in FOUND_ROWS().


2 Answers

You can do it with a stored procedure that updates, and then selects the new value into an output parameter. The following returns one column new_score with the new value.

DELIMITER $$   -- Change DELIMITER in order to use ; withn the procedure CREATE PROCEDURE increment_score (    IN id_in INT ) BEGIN     UPDATE item SET score = score + 1 WHERE id = id_in;     SELECT score AS new_score FROM item WHERE id = id_in; END $$            -- Finish CREATE PROCEDURE statement DELIMITER ;   -- Reset DELIMITER to standard ; 

In PHP:

$result = mysql_query("CALL increment_score($id)"); $row = mysql_fetch_array($result); echo $row['new_score']; 
like image 114
Michael Berkowski Avatar answered Oct 02 '22 22:10

Michael Berkowski


No, there's nothing like postgresql's UPDATE ... RETURNING output_expression in MySQL (yet?).

like image 24
VolkerK Avatar answered Oct 02 '22 23:10

VolkerK