我可以更新INT值+ 1并返回新值吗? [英] Can I update an INT value + 1 and return the new value?

查看:87
本文介绍了我可以更新INT值+ 1并返回新值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL + PHP中是否可以增加INT值并在一个查询中返回新值?

Is it possible in MySQL+PHP to increase an INT value and return the new value within one query?

$sql = mysql_query("UPDATE table SET number=number+1 WHERE id='uniqid'");

$updated_number = ???

或者我需要发布另一个查询?

Or I need to post another query?

SELECT number FROM table WHERE id='uniqid'


推荐答案

简单回答 - 不,这是不可能的。

Simple answer - no, it's not possible.

更长的答案,是的,如果您使用增加值的存储过程指定的ID,检索新值并返回它。

Longer answer, yes, if you use a stored procedure that increments the value for the specified ID, retrieves the new value and returns it.

我刚刚在MySQL 5.1.59下测试了这个:

I've just tested this under MySQL 5.1.59:

CREATE PROCEDURE increment (IN uniqid VARCHAR(255))
BEGIN
   UPDATE `table` SET number = number + 1 WHERE id = uniqid;
   SELECT number FROM `table` WHERE id = uniqid;
END

用法:

CALL increment(uniqid)

如果可以同时进行多次访问你可能希望 LOCK 该表首先确保操作的原子性--MySQL显然不允许存储过程自己锁定表。

If multiple simultaneous accesses are possible you may wish to LOCK the table first to ensure the operation's atomicity - MySQL apparently doesn't allow stored procedures to lock tables themselves.

这篇关于我可以更新INT值+ 1并返回新值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆