UPDATE devices
SET `status` = 'EXP'
WHERE EXISTS
(
SELECT 1
FROM drivers
JOIN device_drivers
ON drivers.id = device_drivers.driver_id AND
device_drivers.device_id = devices.id
WHERE drivers.`expiration date` < now()
);
CREATE TABLE Devices (
device_id INT PRIMARY KEY,
status ENUM('ACTIVE', 'EXPIRED')
);
CREATE TABLE Drivers (
driver_id INT PRIMARY KEY,
device_id INT,
expiration_date DATE,
FOREIGN KEY (device_id) REFERENCES Devices(device_id)
);
您需要遍历每个驱动程序,查看是否已过期并正确更新设备。
首先,您需要在数据库中启用 EVENTS:
SET GLOBAL event_scheduler = ON;
接下来,您可以创建一个每天运行的 event,检查所有 active 设备的 expired 驱动程序并进行适当的更新:
DELIMITER //
CREATE EVENT UpdateDeviceStatus
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_DATE
DO
BEGIN
UPDATE Devices d
SET d.status = 'EXPIRED'
WHERE EXISTS (
SELECT 1 FROM Drivers dr
WHERE dr.device_id = d.device_id
AND dr.expiration_date < CURRENT_DATE
) AND d.status = 'ACTIVE';
END;
//
DELIMITER ;
这是您的事件需要执行的查询:
UPDATE devices SET `status` = 'EXP' WHERE EXISTS ( SELECT 1 FROM drivers JOIN device_drivers ON drivers.id = device_drivers.driver_id AND device_drivers.device_id = devices.id WHERE drivers.`expiration date` < now() );至于事件的创建,您有多种选择,其中一些列在这里:
无论如何,您可能希望将您的
UPDATE包装在一个 存储过程 中,而且如果有更多的写操作,您可能还希望在调用此事件时包装一个 事务。好的,考虑以下
MySQL表结构:CREATE TABLE Devices ( device_id INT PRIMARY KEY, status ENUM('ACTIVE', 'EXPIRED') ); CREATE TABLE Drivers ( driver_id INT PRIMARY KEY, device_id INT, expiration_date DATE, FOREIGN KEY (device_id) REFERENCES Devices(device_id) );您需要遍历每个驱动程序,查看是否已过期并正确更新设备。
首先,您需要在数据库中启用
EVENTS:接下来,您可以创建一个每天运行的
event,检查所有active设备的expired驱动程序并进行适当的更新:DELIMITER // CREATE EVENT UpdateDeviceStatus ON SCHEDULE EVERY 1 DAY STARTS CURRENT_DATE DO BEGIN UPDATE Devices d SET d.status = 'EXPIRED' WHERE EXISTS ( SELECT 1 FROM Drivers dr WHERE dr.device_id = d.device_id AND dr.expiration_date < CURRENT_DATE ) AND d.status = 'ACTIVE'; END; // DELIMITER ;