在存储的触发器中执行查询更新表的问题

时间:2015-12-23 22:13:33

标签: php mysql triggers

我试图从PHP执行此自动生成查询但它无法正常工作

INSERT INTO mvt (id_piece, article_id_article, code_mvt, origine_mvt, type_mvt, code_art, des_art, qte_old, qte_mvt, qte_new, link_piece)
    SELECT 
        32,
        57,     
        'MVT/15/12/0001',
        'BSR/15/12/001',
        'S',
        'ART_039',
        'AAAA',
        a.qte_art,
        1,
        a.qte_art - 1,
        'uuuu'
    FROM article a
    WHERE a.id_article = 57

表格mvt

的结构
CREATE TABLE IF NOT EXISTS `mvt` (
  `id_mvt` int(11) NOT NULL AUTO_INCREMENT,
  `id_piece` int(10) NOT NULL,
  `code_mvt` varchar(20) NOT NULL,
  `origine_mvt` varchar(100) NOT NULL,
  `date_mvt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `type_mvt` varchar(20) NOT NULL,
  `article_id_article` int(10) unsigned NOT NULL,
  `code_art` varchar(20) NOT NULL,
  `des_art` varchar(255) NOT NULL,
  `qte_old` double NOT NULL,
  `qte_mvt` double NOT NULL,
  `qte_new` double NOT NULL,
  `link_piece` varchar(255) NOT NULL,
  PRIMARY KEY (`id_mvt`),
  KEY `article_id_article` (`article_id_article`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=229 ;

mvt

的触发器
DROP TRIGGER IF EXISTS `before_insert_mvt`;
DELIMITER //
CREATE TRIGGER `before_insert_mvt` BEFORE INSERT ON `mvt`
 FOR EACH ROW BEGIN
    UPDATE article  SET qte_art = NEW.qte_new WHERE id_article = NEW.article_id_article;
END

表格article

的结构
CREATE TABLE IF NOT EXISTS `article` (
  `id_article` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `famille_id_famille` int(10) unsigned NOT NULL,
  `marque_id_marque` int(10) unsigned NOT NULL,
  `tva_id_tva` int(10) unsigned NOT NULL,
  `code_art` varchar(20) DEFAULT NULL,
  `des_art` varchar(255) DEFAULT NULL,
  `paht_art` double DEFAULT NULL,
  `pamp_art` double DEFAULT NULL,
  `qte_art` double DEFAULT NULL,
  `seuil_alert` double NOT NULL,
  `seuil_reap` double NOT NULL,
  `date_modif` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `etat` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id_article`),
  KEY `article_FKIndex1` (`tva_id_tva`),
  KEY `article_FKIndex2` (`marque_id_marque`),
  KEY `article_FKIndex3` (`famille_id_famille`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=82 ;

这是sql错误

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

它不起作用! 我错过了什么?

1 个答案:

答案 0 :(得分:2)

触发器正在尝试更新您从中获取插入数据的相同表格,并且不允许这样做。您可以使用临时表分两步完成。

CREATE TEMPORARY TABLE temp_mvt AS
SELECT 
    32,
    57,     
    'MVT/15/12/0001',
    'BSR/15/12/001',
    'S',
    'ART_039',
    'AAAA',
    a.qte_art,
    1,
    a.qte_art - 1,
    'uuuu'
FROM article a
WHERE a.id_article = 57;

INSERT INTO mvt SELECT * FROM temp_mvt;

DROP TABLE temp_mvt;