简体   繁体   中英

Mysql change one column value based on another column

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.

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;

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM