Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

dynamic - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...