Guys I'm exploring triggers in MySQL and I'm a bit confused. I have created this tables:
persons
pid #primary key
last_name
first_name
then this table:
employee_hierarchy
emp_id #primary key
pid #foreign key
role
And created this trigger:
CREATE TRIGGER after_person_insert
AFTER INSERT ON persons
FOR EACH ROW
INSERT INTO employee_hierarchy
VALUES('','LAST_INSERT_ID()','employee');
TRIGGER Successfully created. But whenever I try to insert to persons table, i got a foreign key something error. So I dropped the foreign key and it was a success. But whats the use of this trigger thingy? Can you site a good example where this is useful? cause maybe this is not designed to update foreign keys, i dont know.
Instead of trying to get a value from LAST_INSERT_ID()
(BTW you insert a string since it is in quotes) you just need need to read assigned value from NEW.pid
. It is available to you at this point AFTER INSERT
of time.
CREATE TRIGGER after_person_insert
AFTER INSERT ON persons
FOR EACH ROW
INSERT INTO employee_hierarchy
VALUES(NULL, NEW.pid, 'employee');
Here is SQLFiddle demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.