计算具有3个列值的行的出现次数相同的MySQL

问题描述 投票:0回答:1

MySQL BEFORE INSERT触发器

我有一张bookings表。我有3列叫

facility_id, booking_date, time_slot

我还有一个名为facility的表,其中有一个名为facility_id的列。它们由WHERE bookings.faciliy_id = facility.facility_id联系在一起

我试图计算重复预订表中3列的发生时间,即:

1, 2017-02-02,08:00
1, 2017-02-02,08:00

我希望这是2。

然后我试图检查这个结果,看它是否> =到设施表中存储的设施容量。如果为true,则抛出错误消息。

DELIMITER
//
 CREATE TRIGGER facility_full BEFORE INSERT ON bookings
    FOR EACH ROW
        BEGIN 
        SELECT DISTINCT facility_id, booking_date, timeslot, COUNT(*) FROM bookings 
        SET COUNT = Answer
            IF (Answer) >=  facility_capacity
            THEN  SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Facility Full';
            WHERE bookings.facility_id = facility.facility_id;
            END IF;
    END 
 //
 DELIMITER ;
mysql triggers count where sql-insert
1个回答
0
投票

如你所说,计算重复预订表中3列的时间。这是解决问题的一种方法。

DELIMITER
//
 CREATE TRIGGER facility_full BEFORE INSERT ON bookings
    FOR EACH ROW
        BEGIN 
        DECLARE v_count int;
        Declare msg TEXT;
        DECLARE v_facility_capacity  int;


        select count(*) into v_count from bookings where facility_id = New.facility_id and booking_date  = new.booking_date  and time_slot = new.time_slot;

select facility_capacity  into v_facility_capacity from facility 
where facility.facility_id = New.facility_id;

            IF (v_count) >=  v_facility_capacity  THEN
            set msg = concat('MyTriggerError: Facility Full: ', cast(new.facility_id as char));
            signal sqlstate '45000' set message_text = msg;
            END IF;
    END 
 //
 DELIMITER ;
© www.soinside.com 2019 - 2024. All rights reserved.