如何在MySQL中增加计数器并返回值 [英] How to increment a counter and return the value in MySQL
问题描述
我有一个包含Key列和Counter列的表.我需要做这样的事情:
I have a table that has a Key column and a Counter column. I need to do something like this:
SELECT counter=counter+1 FROM table WHERE key='mykey'
基本上,我需要增加Counter列并返回新值.如何在MySQL 5.5中做到这一点?
Basically, I need to increment the Counter column and return the new value. How can I do this in MySQL 5.5?
推荐答案
update mytable set count=last_insert_id(counter+1) where key='mykey'
然后
select last_insert_id()
可以向
last_insert_id()
传递参数以对其进行设置"(并返回该值),并且不带参数调用该参数将再次返回该值. last_insert_id()
使用的内部状态是每个连接,这意味着在另一个连接上发出的同一update
语句不会影响第一个连接.
last_insert_id()
can be passed an argument to 'set' it (and return that value), and calling it without an argument will return the value again. The internal state used by last_insert_id()
is per-connection, which means that the same update
statement issued on another connection will not affect the first.
参考: last_insert_id()
这篇关于如何在MySQL中增加计数器并返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!