尚未创建MYSQL触发器

时间:2018-05-29 06:05:54

标签: mysql triggers

我很难理解在下面的代码中创建触发器的问题:请协助。

CREATE TABLE staff (staff_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, 
firstname VARCHAR(20)
, lastname VARCHAR(20), email VARCHAR(50));
INSERT INTO staff (firstname, lastname, email)
VALUES ('James', 'Kirby', 'jkirby@test.com'),
    ('Betty', 'Featherstone', 'bfeatherstone@test.com');
CREATE TABLE users (user_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, 
username
 VARCHAR(20), email VARCHAR(50), 
staff_id INT,  FOREIGN KEY (staff_id) REFERENCES staff (staff_id))

DELIMITER //

CREATE TRIGGER after_staff_insert AFTER INSERT ON staff
 FOR EACH ROW
 BEGIN
INSERT INTO users (username, email)
VALUES(CONCAT(NEW.firstname,NEW.lastname,NEW.staff_id),NEW.email);
 END //

DELIMITER;

1 个答案:

答案 0 :(得分:0)

我提到代码块按预期工作后,我无法重现您的问题。你使用什么ide(phpmyadmin,mysqlworkbench)等

drop table if exists s,u;

CREATE TABLE s (staff_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, 
firstname VARCHAR(20)
, lastname VARCHAR(20), email VARCHAR(50));

CREATE TABLE u (user_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, 
username
 VARCHAR(20), email VARCHAR(50), 
staff_id INT,  FOREIGN KEY (staff_id) REFERENCES staff (staff_id));

drop trigger if exists after_staff_insert;
truncate table debug_table;
DELIMITER //

CREATE TRIGGER after_staff_insert AFTER INSERT ON s
 FOR EACH ROW
 BEGIN
INSERT INTO u (username, email,staff_id)
VALUES(CONCAT(NEW.firstname,NEW.lastname,NEW.staff_id),NEW.email,new.staff_id);

 END //
 delimiter ;

INSERT INTO s (firstname, lastname, email)
VALUES ('James', 'Kirby', 'jkirby@test.com'),
    ('Betty', 'Featherstone', 'bfeatherstone@test.com');


 select * from s;
 select * from u;

MariaDB [sandbox]>  select * from s;
+----------+-----------+--------------+------------------------+
| staff_id | firstname | lastname     | email                  |
+----------+-----------+--------------+------------------------+
|        1 | James     | Kirby        | jkirby@test.com        |
|        2 | Betty     | Featherstone | bfeatherstone@test.com |
+----------+-----------+--------------+------------------------+
2 rows in set (0.02 sec)

MariaDB [sandbox]>  select * from u;
+---------+--------------------+------------------------+----------+
| user_id | username           | email                  | staff_id |
+---------+--------------------+------------------------+----------+
|       1 | JamesKirby1        | jkirby@test.com        |        1 |
|       2 | BettyFeatherstone2 | bfeatherstone@test.com |        2 |
+---------+--------------------+------------------------+----------+
2 rows in set (0.00 sec)