简体   繁体   English

MySQL创建带有2个表的触发器

[英]MySQL creating a trigger with 2 tables

I'm creating a trigger that will prevent the booking of a flight if that flight has already left and I'm having some trouble. 我正在创建一个触发器,如果​​该航班已经离开并且遇到一些麻烦,它将阻止该航班的预订。 I'm getting the error message 1109 and I'm not sure if I can join tables in a trigger. 我收到错误消息1109,并且不确定是否可以在触发器中加入表。 This is what the tables look like: 表格如下所示:

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

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

And lastly, my code; 最后,我的代码;

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 ;

Full error message: "Error Code: 1109. Unknown table 'flights' in field list" 完整的错误消息:“错误代码:1109。字段列表中的未知表'航班'

You need to tell the trigger which row of the flights table to look at: 你需要告诉触发的哪一行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 $$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM