我正在努力使用触发器根据正在更新的第一个表更新第二个表。
我试过这个:
DELIMITER //
FOR EACH ROW
BEGIN
Update phpfb_picks
set points = NEW.value
where username = user and gameid = gameid
END;
//
delimiter;
但是语法错误。
如果我这样做:
Update phpfb_picks
set points = NEW.value
where username = user and gameid = gameid
这很有用。它使用更新的相同值更新所有用户记录。
我想要做的是,当表A中的某个值更新时,我想更新表B中包含该用户的所有记录,基本上是'值'来自表A总是会被推到'点'无论实际记录是否更新,用户的表B都是。
如果更新了用户的任何记录,请根据用户名和gameid更新具有相同值的所有表B记录
因此,如果表A具有以下记录: 用户名 - 测试 gameid - 1 价值 - 1
用户名 - 测试 gameid - 2 价值 - 2
当第1行的值更新为3时,我想使用表A中该用户的所有当前值更新表B.
这甚至可能吗?
更新:
Table A (allpoints) has columns:
username
gameid
value
TABLE B (phpfb_picks) has columns:
user
gameid
points
allpoints.username = phpfb_picks.user
allpoints.gameid = phpfb_picks.gameid
allpoints.value = phpfb_picks.points
每当对所有点进行更新时,我希望该特定用户的所有记录在phpfb_picks中更新该用户的所有特定记录,并根据用户和gameid将allpoints.value传递给phpfb_picks.points
答案 0 :(得分:1)
尝试此触发器:
DELIMITER $$
CREATE TRIGGER update_phpfb_picks
AFTER UPDATE ON allpoints FOR EACH ROW
BEGIN
UPDATE phpfb_picks
INNER JOIN allpoints ON allpoints.username = phpfb_picks.username AND
allpoints.gameid = phpfb_picks.gameid
SET phpfb_picks.points = allpoints.value
WHERE phpfb_picks.username = NEW.username;
END;
$$
DELIMITER ;
对于allpoints
中更新的每一行,phpfb_picks
中具有相同更新行用户名的所有行都将更新为points
中相应的值allpoints
作为value
。触发器为AFTER UPDATE
,因此allpoints
中新更新的值也将设置为phpfb_picks
。
答案 1 :(得分:0)
也许这个
drop trigger if exists phpfb;
DELIMITER $$
create trigger phpfb after update on allpoints
FOR EACH ROW
BEGIN
Update phpfb_picks
set points = NEW.value
where user = new.username and gameid = new.gameid;
END $$
delimiter ;
例如
drop table if exists allpoints,phpfb_picks;
create table allpoints (username char(4),gameid int, value int);
create table phpfb_picks (user char(4),gameid int, points int);
insert into allpoints (username,gameid) values
('test',1),('test',2);
insert into phpfb_picks (user,gameid) values
('test',1),('test',1),('test',2);
update allpoints
set value = 2 where username = 'test' and gameid = 1;
结果
+------+--------+--------+
| user | gameid | points |
+------+--------+--------+
| test | 1 | 2 |
| test | 1 | 2 |
| test | 2 | 0 |
+------+--------+--------+
3 rows in set (0.00 sec)