我有两个看起来像这样的桌子
培养
+----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | TrainID | varchar(11) | NO | PRI | NULL | | | Capacity | int(11) | NO | | 50 | | +----------+-------------+------+-----+---------+-------+
订座
+---------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-------------+------+-----+---------+----------------+ | ReservationID | int(11) | NO | PRI | NULL | auto_increment | | FirstName | varchar(30) | NO | | NULL | | | LastName | varchar(30) | NO | | NULL | | | DDate | date | NO | | NULL | | | NoSeats | int(2) | NO | | NULL | | | Route | varchar(11) | NO | | NULL | | | Train | varchar(11) | NO | | NULL | | +---------------+-------------+------+-----+---------+----------------+
当前,我正在尝试创建一个查询,如果取消预订,该查询将增加火车的容量。我知道我必须执行Join,但是我不确定如何在Update语句中执行。例如,我知道如何使用给定的ReservationID来获取火车的容量,如下所示:
select Capacity from Train Join Reservations on Train.TrainID = Reservations.Train where ReservationID = "15";
但我想构造执行此操作的查询-
Increment Train.Capacity by ReservationTable.NoSeats given a ReservationID
如果可能的话,我想知道如何增加任意数量的席位。顺便说一句,我计划在Java事务中执行增量后删除保留。删除会影响交易吗?
谢谢您的帮助!
MySQL支持多表UPDATE语法,大致类似于:
UPDATE
UPDATE Reservations r JOIN Train t ON (r.Train = t.TrainID) SET t.Capacity = t.Capacity + r.NoSeats WHERE r.ReservationID = ?;
您可以在同一事务中更新Train表和从Reservations表中删除。只要您先进行更新,然后再进行删除,它就可以工作。
Train
Reservations