添加新记录时插入到另一个表的触发器

时间:2014-06-25 05:13:18

标签: mysql phpmyadmin

我有2张桌子。利润表数据来自赌注表。因此,只要在赌桌上添加新记录,就可以自动将INSERT转换为利润表。

如何确保触发器仅插入利润表中不存在的数据?

这是我到目前为止所做的事情

DELIMITER $$
DROP TRIGGER IF EXISTS tsuika $$
CREATE TRIGGER keisan BEFORE INSERT ON profitdb
FOR EACH ROW BEGIN
INSERT INTO `profitdb`(`BetID`,`DateTime`, `PlayerID`,
`Profit`,`SubAgentID`,`SubAgentRisk`,`AgentID`,`AgentRisk`)
SELECT `betdb`.`BetID`,`betdb`.`DateTime`,`betdb`.`PlayerID`,
(`BetAmount`-Payout`),`playerdb`.`SubAgentID`,`subagentdb`.`Risk`,
`agentdb`.`AgentID`,`agentdb`.`Risk` FROM `betdb` LEFT JOIN `playerdb` ON
`betdb`.`PlayerID` = `playerdb`.`PlayerID` LEFT JOIN `subagentdb` ON
`subagentdb`.`SubAgentID` = `playerdb`.`SubAgentID` LEFT JOIN `agentdb` ON
`agentdb`.`AgentID` = `playerdb`.`AgentID`
END
$$
DELIMITER;

我提到了这个链接MySQL trigger On Insert/Update events关于使用INSERT制作触发器但仍然出现此错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 5

1 个答案:

答案 0 :(得分:0)

您必须使用默认分隔符结束所有可执行语句,即代码块中的';'分号。 在select陈述后你错过了分号。

您正在尝试删除无关的触发器'tsuika'。它应该是您尝试创建或重新定义的当前触发器。将其更改为'keisan'

DELIMITER $$

DROP TRIGGER IF EXISTS keisan; $$ -- <--- this was with wrong trigger name. corrected.

CREATE TRIGGER keisan BEFORE INSERT ON profitdb
FOR EACH ROW BEGIN
  INSERT INTO `profitdb`(`BetID`,`DateTime`, `PlayerID`, `Profit`,  
                         `SubAgentID`,`SubAgentRisk`,`AgentID`,`AgentRisk`)
         SELECT `betdb`.`BetID`, `betdb`.`DateTime`, `betdb`.`PlayerID`,
                ( `BetAmount` - `Payout` ), `playerdb`.`SubAgentID`,
                `subagentdb`.`Risk`, `agentdb`.`AgentID`, `agentdb`.`Risk` 
           FROM `betdb` 
                 LEFT JOIN `playerdb` 
                        ON `betdb`.`PlayerID` = `playerdb`.`PlayerID` 
                 LEFT JOIN `subagentdb` 
                        ON `subagentdb`.`SubAgentID` = `playerdb`.`SubAgentID` 
                 LEFT JOIN `agentdb` 
                        ON `agentdb`.`AgentID` = `playerdb`.`AgentID`; -- <--- missed
END;

$$

DELIMITER ;