Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL default value as other field's value

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!

like image 518
arik Avatar asked Jun 16 '11 20:06

arik


People also ask

How do I change the default value in mysql?

To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants. For example, you cannot set the default for a date-valued column to NOW( ) , although that would be very useful.

How do I set a default field value?

Set a default valueIn the Navigation Pane, right-click the table that you want to change, and then click Design View. Select the field that you want to change. On the General tab, type a value in the Default Value property box. The value you that you can enter depends on the data type that is set for the field.

Can we set a default value of integer for a table column of datatype datetime?

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE . The exception is that, for TIMESTAMP and DATETIME columns, you can specify CURRENT_TIMESTAMP as the default.


1 Answers

I see two possible solutions for this:

1. Possibility:

You use a function to simply ignore sort_num if it is not set:

`SELECT * FROM mytable ORDER BY coalesce(sort_num, id)`

coalesce() returns the first non-null value, therefore you would insert values for sort_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:

DELIMITER //

CREATE TRIGGER sort_num_trigger
BEFORE INSERT ON mytable
FOR EACH ROW BEGIN
    DECLARE auto_inc INT;
    IF (NEW.sort_num  is null) THEN
         -- determine next auto_increment value
        SELECT AUTO_INCREMENT INTO auto_inc FROM information_schema.TABLES
        WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME = 'mytable';
        -- and set the sort value to the same as the PK
        SET NEW.sort_num = auto_inc;
    END IF;
END
//

(inspired by this comment)

However, this might run into parallelization issues (multiple queries inserting at the same time)

like image 184
Dan Soap Avatar answered Sep 29 '22 20:09

Dan Soap