Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL auto increase column entity by 1 on update?

I have a table: ID,name,count,varchar(255)

Now, what i'd like is to increase the "count" each time that row in the table is updated.

Of course, the easy way is to read first, get the value, increase by 1 in php, then update with the new value. BUT!

is there any quicker way to do it? is there a system in mysql that can do the ++ automatically? like autoincrement, but for a single entity on itself?

like image 990
David19801 Avatar asked Dec 28 '10 12:12

David19801


People also ask

How do I make a column auto increment in MySQL?

Syntax. In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

Can we insert auto increment value in MySQL?

Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How update a column with auto increment in SQL Server?

ALTER TABLE Inventory MODIFY COLUMN item_number INT AUTO_INCREMENT=50; After running this code, future item IDs will start at an item_number of 50 and increment by 1. To change the starting increment value and increment in SQL Server, set your non-default values during table creation.

How do I add an auto increment to an existing column?

Here's the SQL statement to add AUTO INCREMENT constraint to id column. ALTER TABLE sales MODIFY id INT NOT NULL AUTO_INCREMENT PRIMARY KEY; Next we will add a couple of rows in sales table. As you can see, the MySQL has automatically increased and populated id column with values 7 and 8.


2 Answers

I see two options:

1.

Just add this logic to every update query

UPDATE `table` SET
   `data` = 'new_data',
   `update_counter` = `update_counter` + 1
WHERE `id` = 123

2.

Create a trigger that will do the work automatically:

CREATE TRIGGER trigger_name
AFTER UPDATE
ON `table`
FOR EACH ROW
    BEGIN
        UPDATE `table`
        SET `update_counter` = `update_counter` + 1
        WHERE `id` = NEW.id
    END
like image 82
Silver Light Avatar answered Oct 01 '22 01:10

Silver Light


Create a trigger: http://dev.mysql.com/doc/refman/5.1/en/create-trigger.html

Triggers are pieces of code that are "triggered" by the database on certain events. In your case, the event would be an update. Many RDBMS support triggers, so does MySQL. The advantage of using a trigger is that every piece of your PHP logic that updates this entity, will implicitly invoke the trigger logic, you don't have to remember that anymore, when you want to update your entity from a different piece of PHP logic.

like image 23
Lukas Eder Avatar answered Oct 01 '22 00:10

Lukas Eder