我需要构建一个单一的触发器,当一个飞行员已被分配给一个包机时,该飞行员将飞行员指定为副驾驶

时间:2017-10-09 17:55:02

标签: mysql database triggers

DROP TRIGGER IF EXISTS COPILOT_ASSIGNED;

DELIMITER //
CREATE TRIGGER COPILOT_ASSIGNED 
    BEFORE INSERT ON crew 
    FOR EACH ROW
BEGIN
    IF CHAR_TRIP EXISTS AND CREW_JOB = 'Pilot'
    THEN SET NEW.CREW_JOB = 'Copilot';
    END IF;
END //
DELIMITER ; 

INSERT INTO crew VALUES (10019, 109, 'Pilot');
INSERT INTO crew VALUES (10019, 106, 'Pilot');

SELECT * FROM crew WHERE CHAR_TRIP = 10019;

我无法确定如何编写此触发器。我需要检查章程(CREW_TRIP)是否已经分配了一个飞行员(CREW_JOB)。如果是这样,那么飞行员需要改为副驾驶(CREW_JOB)。

1 个答案:

答案 0 :(得分:0)

DROP TRIGGER IF EXISTS COPILOT_ASSIGNED;

DELIMITER //
CREATE TRIGGER COPILOT_ASSIGNED 
    BEFORE INSERT ON crew 
    FOR EACH ROW
BEGIN
    IF EXISTS (SELECT * FROM crew WHERE CHAR_TRIP = NEW.CHAR_TRIP AND 
CREW_JOB='Pilot')
    THEN SET NEW.CREW_JOB = 'Copilot';
    END IF;
END //
DELIMITER ; 

INSERT INTO crew VALUES (10019, 109, 'Pilot');
INSERT INTO crew VALUES (10019, 106, 'Pilot');