我有两个表,但是我想设置一个触发器。当我在表users
中插入新用户时,我想将该id
复制到另一个表results
中。
表users
:
| userID | name | email | password |
+--------+----------+-------------------+----------+
| 1 | Person A | mailA@gmail.com | 12345 |
+--------+----------+-------------------+----------+
| 2 | Person B | mailB@yahoo.com | 13579 |
+--------+----------+-------------------+----------+
| 3 | Person C | mailC@outlook.com | 24681 |
+--------+----------+-------------------+----------+
表results
:
| resultID | userID | TestA | TestB |
+----------+--------+-------+-------+
| 162 | 1 | 84 | 63 |
+----------+--------+-------+-------+
| 028 | 2 | NULL | 54 |
+----------+--------+-------+-------+
| 821 | 3 | 77 | 60 |
+----------+--------+-------+-------+
我想在插入后将userID
从表users
复制到表userID
的{{1}}。
我使用触发器尝试了各种选项,但没有解决问题的方法。
其中之一是:
results
可能是我的结构不符合指导原则,但这是一个概念。
答案 0 :(得分:1)
我仍然不确定我是否理解这个问题,但这是用于对话的代码段
drop table if exists us,res;
create table us (id int);
create table res (id int);
drop trigger if exists t;
delimiter $$
create trigger t after insert on us
for each row
begin
insert into res(id) values (new.id);
end $$
delimiter ;
insert into us values (1);
select * from us;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
select * from res;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
答案 1 :(得分:0)
我已经编写了以下代码段,但是我不知道从哪里获得测试结果!
CREATE TABLE IF NOT EXISTS users (
userID INT(6) UNSIGNED PRIMARY KEY,
name VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255)
);
CREATE TABLE IF NOT EXISTS results (
resultID INT(6) UNSIGNED PRIMARY KEY,
userID VARCHAR(255),
TestA VARCHAR(255),
TestB VARCHAR(255)
);
/* trigger query */
CREATE TRIGGER new_user_added
AFTER INSERT ON users
FOR EACH ROW
INSERT INTO results values('162', NEW.userID, '84', '63');
/* insert query */
replace into users values('1', 'Person A', 'mailA@gmail.com', '12345');
select * from users;
select * from results
用户
| userID | name | email | password |
+--------+----------+-------------------+----------+
| 1 | Person A | mailA@gmail.com | 12345 |
+--------+----------+-------------------+----------+
结果
| resultID | userID | TestA | TestB |
+----------+--------+-------+-------+
| 162 | 1 | 84 | 63 |
+----------+--------+-------+-------+
希望这会有所帮助。