这是我的表格的最小版本:
CREATE TABLE posts (
id int unsigned PRIMARY KEY auto_increment,
root_id int unsigned,
parent_id int unsigned
);
数据是树形结构,所以parent_id
字段包含显而易见的内容,root_id
字段包含根帖子的id,即最顶层树中的帖子,树中最古老的祖先。
现在,当我插入一个本身就是新树的根的新帖子时,parent_id
将为 null,因为它没有父级,但 root_id
应该指的是它本身。有没有办法进行插入,将相同的 id
值放入 root_id
中?我想避免执行插入、获取新 id 并使用第二个查询更改根 id,但也许这是唯一的方法。
提前致谢。
最佳答案
您可以使用触发器在插入
后立即更新表
delimiter |
CREATE TRIGGER update_root AFTER INSERT on posts
FOR EACH ROW
BEGIN
if NEW.parent_id IS NULL
then
SET NEW.root_id = NEW.id;
end if;
END
|
delimiter ;
关于mysql - 除了 id 列之外,插入包含该行 id 的另一列的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729991/