MYSQL set default value of column to be new id
unique_id | master_id | othercolumns
If unique_id
is a 开发者_如何学Ccolumn with auto increment, is there a way to have the column master_id default value be the unique_id when inserting a new record?
I take it "unique_id" and "master_id" are columns. No, you can't have one column default to the value of another, but you can create a trigger to set master_id
to the value of unique_id
on insert. Say the default for master_id is 0. Then the following trigger should work:
delimiter ;;
CREATE TRIGGER default_master_id
BEFORE INSERT
ON table_name FOR EACH ROW
IF NEW.master_id = 0 THEN
SET NEW.master_id = last_insert_id()+1 ;
END IF ;;
delimiter ;
insert into table ... set master_id=last_insert_id()+1;
精彩评论