更新后的mysql TRIGGER更新字段

时间:2013-07-26 05:32:04

标签: mysql triggers

我有2张table_plan和kiln_master。

在将pattern和itemno插入today_plan之后,需要从kiln_master 表中选择匹配的 yeild,并将此值更新为today_plan 中的 yeild字段。

我创建了一个触发器

CREATE TRIGGER update_yeild AFTER INSERT ON today_plan
FOR EACH ROW UPDATE today_plan
  SET yeild= (SELECT kiln_master.yeild from kiln_master,today_plan WHERE today_plan.itemno = kiln_master.item  AND  today_plan.pattern = kiln_master.pattern ) WHERE  itemno=new.itemno AND pattern=new.pattern

我的代码有什么问题

today_plan

DROP TABLE IF EXISTS decsys.today_plan;
CREATE TABLE `today_plan` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `belt` varchar(25) NOT NULL,
  `distant` varchar(25) NOT NULL,
  `pjtno` varchar(15) DEFAULT NULL,
  `pattern` varchar(25) NOT NULL,
  `itemno` varchar(25) NOT NULL,
  `pro_qty` varchar(25) NOT NULL,
  `act_qty` varchar(25) NOT NULL,
  `yeild` varchar(25) NOT NULL,
  `remark` varchar(100) NOT NULL,
  `shipment` varchar(15) NOT NULL,
  `temp` varchar(15) NOT NULL,
  `fire_date` date NOT NULL,
  `kiln` varchar(10) DEFAULT NULL,
  `kiln_plan` varchar(15) NOT NULL,
  `kiln_act` varchar(15) NOT NULL,
  `ins_date` date NOT NULL,
  `ins_act` varchar(15) NOT NULL,
  `plandate` date NOT NULL,
  `ship_date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

kiln_master

DROP TABLE IF EXISTS decsys.kiln_master;
CREATE TABLE `kiln_master` (
  `kid` int(7) NOT NULL,
  `pattern` varchar(30) NOT NULL,
  `item` varchar(30) NOT NULL,
  `yeild` double NOT NULL,
  `temp` int(6) NOT NULL,
  `kiln` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

错误

#1442 - Can't update table 'today_plan' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

非常感谢

1 个答案:

答案 0 :(得分:1)

您尝试在插入行后更新该行,是否更好地执行此操作以便插入正确的值?那就像是;

CREATE TRIGGER update_yeild BEFORE INSERT ON today_plan
FOR EACH ROW 
  SET NEW.yeild = COALESCE((SELECT kiln_master.yeild 
                   FROM kiln_master
                   WHERE NEW.itemno = kiln_master.item  
                   AND  NEW.pattern = kiln_master.pattern
                   LIMIT 1), 0);