Get Updated Value in MySQL instead of affected rows

后端 未结 5 524
攒了一身酷
攒了一身酷 2020-11-30 04:59

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

相关标签:
5条回答
  • 2020-11-30 05:23

    If you don't want to run another Query SELECT then here is another way to do it. I have modified Mr. Berkowski code for reference:

    DELIMITER $$
    CREATE PROCEDURE increment_score
    (
       IN id_in INT
    )
    BEGIN
        set @newScore := null;
        UPDATE item SET score = IF((@newScore := score+1) <> NULL IS NULL, @newScore, NULL) WHERE id = id_in;
        SELECT @newScore;
    END
    DELIMITER ;
    
    0 讨论(0)
  • 2020-11-30 05:26

    You can create a trigger, and you will know everything about the modifications.

    0 讨论(0)
  • 2020-11-30 05:32

    No you cant. You could make a function or stored procedure that could do the insert and return the updated value but that would still require you to execute two queries from within the function or stored procedure.

    0 讨论(0)
  • 2020-11-30 05:35

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

    0 讨论(0)
  • 2020-11-30 05:42

    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'];
    
    0 讨论(0)
提交回复
热议问题