MySQL trigger to update a field to the value of id

前端 未结 6 581
臣服心动
臣服心动 2020-11-27 21:21

I would like to have a trigger to perform following operation for inserted records:

 # pseudocode
 if new.group_id is null
    set new.group_id = new.id
 els         


        
6条回答
  •  清酒与你
    2020-11-27 21:30

    This works for me

    DELIMITER $$
    CREATE TRIGGER `myTriggerNameHere`
    BEFORE INSERT ON `table` FOR EACH ROW
    BEGIN
        SET NEW.group_id = IF(NEW.group_id IS NULL, LAST_INSERT_ID()+1, NEW.group_id);
    END;
    $$
    DELIMITER ;
    

提交回复
热议问题