Can I, and, if I can, how can I set the default value of a field in a MySQL table to the value of another field?
Thing is: I have data, and each data object has its ID in the table. But, I would like the possibility to rearrange the data, changing their sorting index, without altering their ID. Thus, the field sort_num
should by default be set to the value given to the auto-incremented indexed field ID
.
Thanks in advance!
I see two possible solutions for this:
1. Possibility:
You use a function to simply ignore
sort_num
if it is not set:coalesce()
returns the first non-null value, therefore you would insert values forsort_num
if you really need to reorder items.2. Possibility:
You write a trigger, which automatically sets the value if it is not set in the insert statement:
(inspired by this comment)
However, this might run into parallelization issues (multiple queries inserting at the same time)
Its a bad idea to have an auto-increment column rearranged, hence better idea would be
Add a column sort_num to the table
Now play with sort_num column as it has no effect on column ID