如果条件有效,则每隔一小时更新现有值

时间:2014-03-12 08:15:50

标签: php mysql sql

如果条件有效,我试图每隔一小时更新现有值

是否可以在事件内写if语句?

CREATE EVENT e_hourly
ON SCHEDULE
  EVERY 1 HOUR
COMMENT 'add one every hour if its lees than 10 '
DO
if score > 10
    UPDATE my_table SET score=score+1 WHERE ID=1

2 个答案:

答案 0 :(得分:1)

当然有可能。您的代码只有三个问题:

CREATE EVENT e_hourly
ON SCHEDULE
  EVERY 1 HOUR /*Problem 1: This is every 1 hour starting from the time you created the event. Probably not what you want.*/
COMMENT 'add one every hour if its lees than 10 '
DO /*Problem 2: You'll have multiple statements here. Tell this MySQL or it will think that your event declaration will be finished after the first statement.*/
if score > 10 /*Problem 3: The computer will ask "which score?"*/
    UPDATE my_table SET score=score+1 WHERE ID=1

编写如下代码:

DELIMITER $$
CREATE EVENT e_hourly
ON SCHEDULE
  EVERY 1 HOUR
  STARTS '2014-03-12 09:00:00'
COMMENT 'add one every hour if its lees than 10 '
DO
BEGIN
SET @my_score = (SELECT score FROM my_table WHERE ID = 1);
IF (@my_score > 10) THEN
    UPDATE my_table SET score=score+1 WHERE ID=1;
END IF;
END $$
DELIMITER ;

答案 1 :(得分:0)

是的,您可以在IF定义中拥有event或任何其他条件和多语句代码块。

如果要处理多个语句,则需要将它们括在begin - end之间。

示例

CREATE EVENT e_hourly
ON SCHEDULE
  EVERY 1 HOUR
COMMENT 'add one every hour if its lees than 10 '
DO
  BEGIN
    if ( score > 10 ) THEN
      UPDATE my_table SET score=score+1 WHERE ID=1;
    elseif  ( score < 10 ) THEN
      -- add your statement here
    else
      -- add your statement here
    end if;
  END;

请参阅