我有两个桌子;
tbl_ride
+---------+--------------+----------+
| rideID | rideName | duration |
+---------+--------------+----------+
| 1 | NY Tour | 3 |
| 2 | Night Life | 2 |
+---------+--------------+----------+
tbl_day
+------------+-----------+----------+
| dayID | rideID | routeMap |
+---------+--------------+----------+
| 1 | 1 | A-B |
| 2 | 1 | B-C |
| 3 | 1 | C-D |
| 4 | 2 | A-B |
| 5 | 2 | B-C |
+---------+--------------+----------+
所以我需要能够基于tbl_day
限制记录到tbl_ride.duration
中的记录数。可以通过SQL来实现还是应该通过代码来实现?无论哪种方式,我都会感谢您的帮助。
以下是我当前用于JDBC的MySQL代码:
INSERT INTO `tbl_tour_day` (`tourID`, `startHotel`, `endHotel`, `routeNote`, `routeMap`)
VALUES ( (SELECT tourID from tbl_tour_ride where tbl_tour_ride.tourID = ?), ?, ?, ?, ?)
以下是有效查询的示例:
INSERT INTO tbl_tour_day
(tourID
,startHotel
,endHotel
,routeNote
,routeMap
)
SELECT tourID
, ?
, ?
, ?
, ?
from tbl_tour_ride
where tbl_tour_ride.tourID = ?
测试
CREATE TRIGGER tr_bi_tbl_day
BEFORE INSERT
ON tbl_day
FOR EACH ROW
BEGIN
IF COALESCE(( SELECT COUNT(*) FROM tbl_day WHERE rideID = NEW.rideID ), 0)
>=
COALESCE(( SELECT MAX(duration) FROM tbl_ride WHERE rideID = NEW.rideID ), 0) THEN
SIGNAL SQLSTATE = '45000'
SET MESSAGE_TEXT = 'All days for this ride has been specified';
END IF;
END
如果tbl_ride
中没有新的rideID
记录,则不允许插入(假定为零)。>>
如果tbl_ride
中有多个记录用于新的rideID
,则将最大值用作限制。