MySQL runs automated scripts
P粉821231319
P粉821231319 2023-08-18 11:24:32
0
2
446
<p>I have a MySQL database with two tables: drivers and devices</p> <p>The drivers table has a field called expiration date. The devices table has a field called status. </p> <p>My goal is to create an event that will:</p> <ul> <li>Get the current date</li> <li>Compare drivers (expiration date) with current date</li> <li>If the expiration date has passed, you need to change the status of the device to 'EXP'</li> </ul> <p>Is such a thing possible? Like an expiration check</p>
P粉821231319
P粉821231319

reply all(2)
P粉831310404

This is the query your event needs to execute:

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()
);

As for event creation, you have several options, some of which are listed here:

Regardless, you may want to wrap your UPDATE in a stored procedure, and if there are more writes, you may also want to call this event when Wrap a transaction.

P粉659516906

Okay, consider the following MySQL table structure:

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)
);

You need to go through each driver to see if it has expired and update the device correctly.

First, you need to enable EVENTS in the database:

SET GLOBAL event_scheduler = ON;

Next, you can create an event that runs daily, checking all active devices for expired drivers and updating them appropriately:

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 ;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!