Reputation: 22956
I have an auto increment column. I want to change value of another column based on this auto increment column value.
another column value ==> (auto increment column value/3) +1
How do I do it via query? Is it possible?
I want to do it for newly creating rows.
Upvotes: 1
Views: 987
Reputation: 4899
It is a "derived" value and you should consider not to store this value but calculate it in your PHP code every time you need it. Here is a post where you can find further explanations about when to store derived values: Storing “derived” values vs calculating them on extraction
@Octopi solution could solve your problem.
Upvotes: 1
Reputation: 4747
Try the following:
INSERT INTO your_table (your_column)
SELECT (MAX(auto_increment_column) / 3) + 2 FROM your_table;
EDIT
If you want to calculate the column depending on the number of values use this:
INSERT INTO your_table (your_column)
SELECT (COUNT(*) / 3) + 2 FROM your_table;
EDIT 2
You can accomplish the same using:
INSERT INTO your_table (your_column) VALUES (
(SELECT (MAX(aa.auto_increment_column) / 3) + 2 FROM your_table AS aa)
);
EDIT 3
For more columns you can use something like this:
INSERT INTO your_table (your_column, some_other_column) VALUES (
(SELECT (MAX(aa.auto_increment_column) / 3) + 2 FROM your_table AS aa), some_other_column
);
You can find more info here: Select from same table as an Insert or Update
In fact you have to add +2 because it's 1 from you rule and +1 to increment the MAX(id).
Upvotes: 0
Reputation: 4098
Is the new (id/3)+1)
value ever going to change?
Judging from the question, the data only exists at the time of the insert. The auto increment column will never change as it has to be a Primary Key, I would only insert on it if you have to join on it or if it is going to change in future. You can get this derived value from a SELECT
query after your insert.
SELECT id, ((id/3)+1) as derived value from table;
Upvotes: 3