我看到两个可能的解决方案:
1.可能性:
如果未设置,则使用函数简单地忽略sort_num:
`SELECT * FROM mytable ORDER BY coalesce(sort_num, id)`
coalesce()返回第一个非null值,因此如果确实需要重新排序项,则应插入sort_num的值.
2.可能性:
您编写了一个触发器,如果??未在insert语句中设置该值,则会自动设置该值:
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
//
但是,这可能会遇到并行化问题(同时插入多个查询)