如何在MySQL中使用计数器创建调度程序?

时间:2019-02-09 19:31:38

标签: mysql sql

在我的 MySQL 数据库中,有一个名为TABLE_MAIN的表。我需要每小时从其他表向该表添加新数据。在我的情况下,它们是TABLE_ATABLE_B。我需要每小时下面运行SQL语句。同时,我需要每小时为A.TIME_KEYB.MONTH_KEY设置新值。

例如,一小时后,A.TIME_KEY的值必须为2018-01-05 01:00:00。同时B.MONTH_KEY具有相同的值2018-01-01B.MONTH_KEY的值仅在下个月更改。例如2018-02-01

如何在MySQL中使用计数器来安排此类计划程序?

SQL

INSERT INTO TABLE_MAIN (
  ID,
  TIME_KEY,
  STATUS,
  OBJECT_NAME,
  OBJECT_DESCRIPTION
) VALUES (
  SELECT
    A.ID
    A.TIME_KEY
    A.STATUS
    B.OBJECT_NAME
    B.OBJECT_DESCRIPTION
  FROM 
    TABLE_A AS A
  INNER JOIN 
    TABLE_B AS B
  ON 
    A.ID = B.ID_OBJECT
  WHERE 
    A.TIME_KEY="2018-01-05 00:00:00"
  AND
    B.MONTH_KEY="2018-01-01"
);

2 个答案:

答案 0 :(得分:1)

您可以按照以下方式进行操作:

首先,您需要构建一个适当的插入查询,然后将其放入事件计划程序中。

打开您的调度程序:

SET GLOBAL event_scheduler = ON;


CREATE 
    EVENT `Event_Name` 
    ON SCHEDULE EVERY 1 HOUR STARTS '2019-02-10 00:00:00' 
    DO BEGIN

    INSERT INTO TABLE_MAIN (
  ID,
  TIME_KEY,
  STATUS,
  OBJECT_NAME,
  OBJECT_DESCRIPTION
) 
      SELECT
    A.ID
    A.TIME_KEY
    A.STATUS
    B.OBJECT_NAME
    B.OBJECT_DESCRIPTION
  FROM 
    TABLE_A AS A
  INNER JOIN 
    TABLE_B AS B
  ON 
    A.ID = B.ID_OBJECT
  WHERE
      CASE WHEN DAY(B.MONTH_KEY) = 1
           THEN  month(B.MONTH_KEY) = month(NOW() - INTERVAL 1 DAY)
           ELSE   month(B.MONTH_KEY) = month(NOW())
      END
     AND
     CASE WHEN HOUR(A.TIME_KEY) < 2
          THEN Date(A.TIME_KEY) = Date(NOW() - INTERVAL 1 DAY) AND hour(A.TIME_KEY) = hour(NOW() - INTERVAL 2 HOUR)
          ELSE Date(A.TIME_KEY) = Date(NOW()) and hour(A.TIME_KEY) = hour(NOW()- INTERVAL 2 HOUR)
     END

答案 1 :(得分:1)

您可以使用DATE_FORMAT()并将DATE或DATETIME的最后一部分设置为恒定值:

WHERE 
    A.TIME_KEY  = DATE_FORMAT(NOW(), '%Y-%m-%d %H-00-00')
  AND
    B.MONTH_KEY = DATE_FORMAT(NOW(), '%Y-%m-01')

如果数据“落后两个小时”,只需将NOW()替换为NOW() - INTERVAL 2 HOUR

WHERE 
    A.TIME_KEY  = DATE_FORMAT(NOW() - INTERVAL 2 HOUR, '%Y-%m-%d %H-00-00')
  AND
    B.MONTH_KEY = DATE_FORMAT(NOW() - INTERVAL 2 HOUR, '%Y-%m-01')