且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以更新INT值+ 1并返回新值吗?

更新时间:2023-12-05 14:04:34

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

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.