MySQL用2个表创建一个触发器

时间:2016-02-14 15:33:03

标签: mysql

我创建了一个触发器,如果​​该航班已经离开且我遇到了麻烦,将阻止预订航班。我收到错误消息1109,我不确定是否可以在触发器中连接表。这就是表格的样子:

预订表:

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

航班表:

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 ;

完整的错误消息:"错误代码:1109。未知的表格'航班'在字段列表"

1 个答案:

答案 0 :(得分:0)

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

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 $$