根据Trigger中的子查询计算值

时间:2015-01-04 20:24:10

标签: mysql mysql-error-1064

我想在MySql中创建一个触发器,在表A中插入一些值,如果记录已经存在,我想重新计算其中一个字段但是我一直收到语法错误:

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'P1

附近使用正确的语法

INNER JOIN ( SELECT SUM(ATS)AS TOTAGAINST,TOURNID,HOMETEAM,ROUNDID'在第6行

这是我的代码(剥离调试):

DROP TRIGGER IF EXISTS `trig_matches_insert`;
DELIMITER //
CREATE TRIGGER `trig_matches_insert` AFTER INSERT ON `matches`
 FOR EACH ROW
BEGIN 
 INSERT INTO  positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values       
(new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY 
UPDATE positions P1
INNER JOIN 
(
 SELECT SUM(ATS) AS TOTAGAINST, TOURNID, HOMETEAM, ROUNDID FROM matches GROUP BY  
 TOURNID,HOMETEAM, ROUNDID
) P2 ON P2.HOMETEAM = P1.TEAMID AND P2.TOURNID = P1.TOURNID AND P2.ROUNDID = P1.ROUNDID
SET P1.SC_AGAINST = P2.TOTAGAINST WHERE P1.ID = 10;
END
//
DELIMITER ;

我不知道这里有什么问题.. 当我单独运行更新查询时,它运行良好

这是一些支持sql:

CREATE TABLE IF NOT EXISTS `matches` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `TOURNID` int(11) NOT NULL,
  `HOMETEAM` int(11) NOT NULL,
  `AWAYTEAM` int(11) NOT NULL,
  `HTS` decimal(10,0) NOT NULL,
  `ATS` decimal(10,0) NOT NULL,
  `FIELD` text NOT NULL,
  `TIME` datetime NOT NULL,
  `ROUNDID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `TOURNID` (`TOURNID`),
  KEY `HOMETEAM` (`HOMETEAM`),
  KEY `AWAYTEAM` (`AWAYTEAM`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;

INSERT INTO `matches` (`ID`, `TOURNID`, `HOMETEAM`, `AWAYTEAM`, `HTS`, `ATS`, `FIELD`, `TIME`, `ROUNDID`) VALUES
(17, 1, 30, 31, '2', '3', '', '2015-01-04 00:00:00', 1),
(18, 1, 30, 3, '2', '4', '', '2015-01-04 00:00:00', 1),
(19, 1, 30, 4, '3', '5', '', '2015-01-04 00:00:00', 1);

CREATE TABLE IF NOT EXISTS `positions` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `TOURNID` int(11) NOT NULL,
  `TEAMID` int(11) NOT NULL,
  `ROUNDID` int(11) NOT NULL,
  `SC_FOR` decimal(10,0) NOT NULL,
  `SC_AGAINST` decimal(10,0) NOT NULL,
  `POULEID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `TOURNID_2` (`TOURNID`,`TEAMID`,`ROUNDID`),
  KEY `TOURNID` (`TOURNID`,`TEAMID`),
  KEY `TEAMID` (`TEAMID`),
  KEY `ROUND` (`ROUNDID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;

   INSERT INTO `positions` (`ID`, `TOURNID`, `TEAMID`, `ROUNDID`, `SC_FOR`, `SC_AGAINST`, `POULEID`) VALUES
(10, 1, 30, 1, '2', '12', 0);

提前致谢

麦克

1 个答案:

答案 0 :(得分:0)

想想我已经找到了它,看起来就像在ON DUPLICATE KEY之后,位置表已经得到了范围,无需从头开始构建和更新语句,看起来像快速选择会做得很好:

DROP TRIGGER IF EXISTS `matches_after_ins_trig`;
DELIMITER //
CREATE TRIGGER `matches_after_ins_trig` AFTER INSERT ON `matches`
FOR EACH ROW
BEGIN 
INSERT INTO  positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values     (new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY UPDATE SC_AGAINST = (SELECT SUM(ATS) FROM matches WHERE  
matches.HOMETEAM = new.HOMETEAM AND matches.TOURNID = new.TOURNID AND
matches.ROUNDID = new.ROUNDID GROUP BY TOURNID,HOMETEAM, ROUNDID);
END