Using auto_increment id field value in other columns in the table
I am using mysql 8.0.30. I have an orders table which is defined as follows:
create table orders (
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
code varchar (64) NOT NULL,
ord_num varchar(512) NOT NULL );
After inserting a rows, I would like to have it as follows:
+----+------+-------+
| id | code | ord_num|
+----+------+-------+
| 1 | abc | abc-1 |
| 2 | def | def-2 |
+----+------+-------+
That is ord_num should have concatenation of code-id. I can achieve that by an update statement as follows:
update orders set ord_num = concat (code, '-', id ) where id = 2;
However, I would like to achieve that in the insert statemenet. For ex:
insert into orders (code, ord_n开发者_如何学Pythonum) values ("xyz", concat(code, '-', id));
This actually results in:
+----+------+-----------+
| id | code | ord_num |
+----+------+-----------+
| 1 | abc | abc-0 |
| 2 | def | def-2 |
| 3 | xyz | xyz-0 |
+----+------+-----------+
I know I can do this by starting a transaction, insert with some dummy value in ord_num, then updating it with the correct value before committing. I would prefer to do it in one insert statement, if possible?
精彩评论