MySQL 创建一个包含 2 个表的触发器

MySQL creating a trigger with 2 tables

我正在创建一个触发器,如果​​该航班已经起飞并且我遇到了一些麻烦,它将阻止该航班的预订。我收到错误消息 1109,我不确定是否可以在触发器中加入 tables。这就是 table 的样子:

预订table:

create table Bookings
(
bookingNumber int not null auto_increment,
timeOfBooking datetime not null,
paymentType bit,    -- 1: credit card.  0: debet card(cash)
cardIssuedBy varchar(35),
cardholdersName varchar(55),
flightCode int not null,
classID int default 3,
returnFLight boolean default true,
constraint booking_PK primary key(bookingNumber),
constraint booking_flight_FK foreign key(flightCode) references   lights(flightCode),
    constraint booking_class_FK foreign key(classID) references Classes(classID)
);

航班 table:

create table Flights
(
flightCode int not null auto_increment,
flightDate date not null,
flightNumber char(5) not null,
aircraftID char(6) not null,
flightTime time,
constraint flightPK primary key(flightCode),
constraint flight_data_UQ unique(flightDate,flightNumber,aircraftID),
constraint flight_flightschedule_FK foreign key(flightNumber) references FlightSchedules(flightNumber),
constraint flight_aircraft_FK foreign key(aircraftID) references Aircrafts(aircraftID)
);

最后,我的代码;

drop trigger if exists check_flightGone;
delimiter $$
create trigger check_flightGone
before insert on bookings
for each row
begin
     declare msg varchar(255);
     if (new.timeOfBooking > Flights.flightDate) then -- eat bananas.
        set msg = concat('The flight you have requested has left you, much like everything else in your life... :^)');
        signal sqlstate '45000' set message_text = msg;
 end if;
end $$

delimiter ;

完整错误信息:"Error Code: 1109. Unknown table 'flights' in field list"

您需要告诉触发器要查看 flights table 的哪一行:

delimiter $$
create trigger check_flightGone
before insert on bookings
for each row
begin
     declare msg varchar(255);
     declare fdate date;
     set fdate = (select flightDate from flights where new.flightCode = flights.flightCode);
     if (new.timeOfBooking > fdate) then -- eat bananas.
        set msg = concat('The flight you have requested has left you, much like everything else in your life... :^)');
        signal sqlstate '45000' set message_text = msg;
 end if;
end $$