未创建mysql触发器

polkgigr  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(366)

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

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;
31moq8wy

31moq8wy1#

我不能重现你的问题后,我提到的代码块的工作预期的变化。您使用的是什么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)

相关问题