将INSERT上的MYSQL UPDATE表插入同一表

看起来很简单,但仍然是一个挑战。我尽可能简化了我的问题。

我有这个test_table和一条记录:

    id | cost_per_record
    1  | 24

插入后,我希望表看起来像这样:

    id | cost_per_record
    1  | 12
    2  | 12

在应用程序中,我无法调用存储过程,因此我在其他程序中使用了以下代码:

    DROP TABLE IF EXISTS `test_table`;
    CREATE TABLE `test_table` (
      `id` int(11) NOT NULL,
      `cost_per_record` int(11) DEFAULT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

    INSERT INTO `test_table` (`id`, `cost_per_record`) VALUES (1,24);

    DELIMITER $$
    CREATE TRIGGER `test_insert` BEFORE INSERT ON `test_table` FOR EACH ROW 
    BEGIN
    update `test_table` set `cost_per_record` = 12 
    where `id`  = 1;
    END
    $$
    DELIMITER ;

    INSERT INTO `test_table` (`id`, `cost_per_record`) VALUES
    (2,12);

我通常会收到的错误(也可能是其他尝试):

    MySQL said: Documentation 

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

Believe me, I read quite some answers on this forum and also ran into blogs saying this is impossible. But I am (still) not accepting this. So.. any solution... thanks...

评论