MySQL default value as other field's value

限于喜欢 提交于 2019-11-28 12:01:22

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)

Its a bad idea to have an auto-increment column rearranged, hence better idea would be

Add a column sort_num to the table

ALTER TABLE data ADD sort_num column-definition; (column definition same as ID)

UPDATE data SET sort_num = ID

Now play with sort_num column as it has no effect on column ID

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!