Question

I have the following tables:

  • Flights (id_flight)

  • Airports (id_airport)

  • Departures_Arrivals (id_flight, id_airport), which is the Junction Table between Flights and Airports and it has the following attributes:

    • gate

    • date

    • type, which can be either 0 or 1, where 0 stands for departure and 1 stands for arrival.

Is there any kind of constraint to make sure that the date of the arrival is greater than the date of the departure?

Was it helpful?

Solution

Make a BEFORE INSERT TRIGGER, which checks in case of an Inserting a row for that flight and Airport the condition is met.

This is an example, you have ti check the conditions and error message if the condition is not met.

DELIMITER $$

CREATE TRIGGER before_Departures_Arrivals_insert
BEFORE INSERT
ON Departures_Arrivals FOR EACH ROW
BEGIN
    DECLARE _date  DATETIME;
    DECLARE _tyoe  INTEGER;

    IF NEW.tyoe = 1 THEN
        SET _type = 0;
    ELSE
        SET _type = 1;
    END IF;

    SELECT `date`
    INTO _date
    FROM Departures_Arrivals 
    WHERE id_flight = NEW.id_flight AND  id_airport = NEW.id_airport
            AND type = _type
    ORDER BY `date` DESC
    LIMIT 1;

    IF NEW.`date` > _date THEN
        SIGNAL SQLSTATE '45000' 
        SET MESSAGE_TEXT = "The new date is before the arrival";
    END IF; 

END $$

DELIMITER ;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top