开发者

MYSQL: Query to update an incremental value and store the returning value

开发者 https://www.devze.com 2023-04-09 05:55 出处:网络
I have a query to substract a value stored on the DB. UPDATE tablename SET available = IF( available > 0, available - \" 开发者_如何学编程. $var . \", 0 ) ,

I have a query to substract a value stored on the DB.

UPDATE tablename SET 
 available = IF( available > 0, available - " 开发者_如何学编程. $var . ", 0 ) , 
 purchases = purchases + 1 
 WHERE condition

Is posible to get the new value of field available without make a new SELECT and then penalize the performance?


You could use a mysql user-defined function:

CREATE FUNCTION registerPurchase(idParam INT, qty INT) 
RETURNS INT
BEGIN
    DECLARE avail INT, purc INT,

    SELECT available, purchases INTO avail, purc FROM tablename WHERE id = idParam;

    SET avail = IF( avail > 0, avail - qty, 0 );
    SET purc = purc - 1;

    UPDATE tablename SET 
     available = avail, 
     purchases = purc
     WHERE id = idParam;

    RETURN avail;
END

Or something like that. You can call this using SELECT registerPurchase(1234, 2);, for example. This could be combined with @Johan's solution for even greater justice.

EDIT:

Here's a link: http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html.


I haven't tested this code, but I'm 87,587% sure it works.

An update statement does not return a resultset, however you can set a @var variable and select from that.

UPDATE tablename 
SET  
  available = @fastpeek:= IF( available > 0, available - " . $var . ", 0 ) 
  ,purchases = purchases + 1 
WHERE condition
LIMIT 1;

SELECT @fastpeek as available_in_update;

This will break if you update more than 1 row however: when updating more than 1 row, @fastpeek will only show the last update. Hence the limit 1.
You still need an extra select, but it will not need to query the database, it will just retrieve the @var from memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号