开发者

How do I plus one in a table column?

I've got a mysql table column that acts as a counter (int). Each time I update that column I want the field value to get plussed with 1开发者_如何学Go.

So if it was 45 I want it to be 46.

How could I do that with SQL?


You can use a query such as this one :

update your_table 
set your_column = your_column + 1 
where identifier = X

Of course, up to you to replace the names of the table and the columns ;-)
And to make sure the condition in the where clause is OK ;-)


MySQL v5.0.2 or higher supports triggers, which are pieces of code that are executed, whenever an insert/update/delete operation is made on one of the rows.

for more information about triggers in MySQL check this link


Since you want it to happen each time, you could use a trigger:

delimiter //
create trigger increment_field before update on your_table
for each row
begin
if new.your_column <> old.your_column then
  set new.your_column = new.your_column + 1
end if;
end;//
delimiter ;

I am not entirely sure I understand your question. The above solution will make it so whenever a row is updated such that your_column is given a different value, it will instead make your_column = new_value+1. The use of new and old keywords and the conditional used on each row should be changed to suit your needs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜