在我的 MySQL 数据库中,有一个名为TABLE_MAIN
的表。我需要每小时从其他表向该表添加新数据。在我的情况下,它们是TABLE_A
和TABLE_B
。我需要每小时下面运行SQL语句。同时,我需要每小时为A.TIME_KEY
和B.MONTH_KEY
设置新值。
例如,一小时后,A.TIME_KEY
的值必须为2018-01-05 01:00:00
。同时B.MONTH_KEY
具有相同的值2018-01-01
。 B.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"
);
答案 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')