I need two columns in table that would have same value on insert. Is there any way to do it from database side?
相关问题
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Why sometimes there is one of more gap(s) in the v
- mySQL alter table on update, current timestamp
Define a before or after insert trigger and assign the value of the 2nd field in the trigger.
If the 1st field is an auto increment column, then you need to use an after insert trigger. If your application assigns value to the 1st field, then you can use a before insert trigger.
However, I would no necessarily duplicate the value on insert. You can leave the 2nd field as null on insert, which would mean that its value is the same as the 1st field's. The only drawback of this approach is that it may be more difficult to create joins on the 2nd field.
So you want to let one column use the auto_increment feature, but make another column in the same table also have the same value?
I can't think of a reason you would need this feature. Perhaps you could explain what you're trying to accomplish, and I can suggest a different solution?
A trigger won't work for this. It's a chicken-and-egg problem:
AFTER
trigger.BEFORE
trigger executes.It also won't work to use a MySQL 5.7
GENERATED
column:You can't do it in a single SQL statement. You have to
INSERT
the row, and then immediately do anUPDATE
to set your second column to the same value.You could alternatively generate the ID value using some other mechanism besides
AUTO_INCREMENT
(for example a Memcached incrementing key). Then you could insert the new value in both columns: