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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算具有3个列值的行的出现次数相同的MySQL相关的知识,希望对你有一定的参考价值。

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 ;
答案

如你所说,计算重复预订表中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 ;

以上是关于计算具有3个列值的行的出现次数相同的MySQL的主要内容,如果未能解决你的问题,请参考以下文章

连接具有相同值的行的列值(不同列的)

如何在MySql中返回具有相同列值的行

SQL如何查询出某一列中不同值出现的次数?

根据另一列的字段值选择具有相同列值的行

在保留列的同时计算具有相同值的行

mysql连接具有相同列值的两行并计算某些列值并返回一行中的所有行