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

时间:2019-03-19 10:15:21

标签: mysql triggers count where sql-insert

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。

然后,我试图检查此结果,以查看其> =是否存储在设施表中的facility_capacity。如果为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 ;

1 个答案:

答案 0 :(得分: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 ;