如何在过程或触发器中创建mysql事件?

最近我一直在寻找以下情况的解决方案:

我有结构的mysql表:

CREATE TABLE IF NOT EXISTS `battles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`begindate` datetime NOT NULL,
`enddate` datetime NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

每场战斗都有乞求和结束. Begindate是插入的日期时间,通常是三天后的结束日期.

我想创建一个mysql事件,在战斗结束时停止战斗(设置active = 0).我希望在战斗表中的插入触发器上创建此事件.

有一个相关的问题很少有答案(here).

他们建议:

You should be able to do it using a trigger and the event scheduler:

  • create a trigger on the table that is fired on every update / insert
  • this trigger creates a scheduled event that occurs at the datetime of the row and updates >your second table

我试图创建这样的查询但没有成功.

DELIMITER |
DROP TRIGGER IF EXISTS battle_create_end|
CREATE TRIGGER battle_create_end AFTER INSERT ON battles
  FOR EACH ROW BEGIN

    CREATE EVENT IF NOT EXISTS CONCAT('battle_end_',NEW.id)
    ON SCHEDULE AT NEW.enddate
    DO
    UPDATE battles SET battles.active = 0 WHERE battles.id = NEW.id;

  END|

DELIMITER ;

我得到的错误是

1576 – Recursion of EVENT DDL statements is forbidden when body is present

我已尝试在每个行结构中使用不同的分隔符,但也没有成功.

如果有人可以提供帮助,请告知.

BR,
Ilko

解决方法:

对不起兄弟,但从我一直在阅读你提出的建议是不可能的.我认为你不能用触发器创建一个事件.这是一个无赖,因为它对我也有用.

但是,当创建每个战斗的行时,创建事件会更容易.听到的是我从一个解释事件如何工作的人发现的一些代码的例子.

<?php
// establish database connection and filter incoming data
// ...
// insert blog post with pending status, get id assigned to post
$query = "INSERT INTO blog_posts (id, title, post_text, status) 
VALUES (NULL, :title, :postText, 'pending')";
$stm = $db->prepare($query);
$stm->execute(array(":title" => $title, ":postText" => $text));
$id = $db->lastInsertId();

// is this a future post?
if (isset($_POST["schedule"], $_POST["time"])) {
$scheduleDate = strtotime($_POST["time"]);

$query = "CREATE EVENT publish_:id
ON SCHEDULE AT FROM_UNIXTIME(:scheduleDate)
DO
  BEGIN
    UPDATE blog_posts SET status = 'published' WHERE id = :id;
  END";
$stm = $db->prepare($query);
$stm->execute(array(":id" => $id, ":scheduleDate" => $scheduleDate));
}
// this is not a future post, publish now
else {
$query = "UPDATE blog_posts SET status = 'published' WHERE id = :id";
$stm = $db->prepare($query);
$stm->execute(array(":id" => $id));
}

所以基本上在向桌面添加战斗时创建事件.

上一篇:在MySQL中,执行触发器需要什么特权?


下一篇:mysql触发器功能