触发以避免冲突

时间:2016-12-29 05:34:34

标签: mysql

我有预订表

id     room     date_IN         date_OUT
 1      101      29-12-2016      1-1-2017
 2      102      29-12-2016      2-1-2017
 3      101      1-1-2017        4-1-2017

如果我将(id = 1)的date_OUT修改为3-1-2017

,如何触发以避免冲突日期

1 个答案:

答案 0 :(得分:1)

您必须创建2个触发器BEFORE INSERTCREATE TABLE booking ( id INT AUTO_INCREMENT PRIMARY KEY, room INT, date_IN date, date_OUT date ); DELIMITER $$ CREATE TRIGGER `booking_duplicate_insert` BEFORE INSERT ON `booking` FOR EACH ROW BEGIN IF EXISTS (SELECT date_IN, date_OUT FROM booking WHERE date_IN <= NEW.date_IN AND date_OUT > NEW.date_OUT) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An error occurred'; END IF; END $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `booking_duplicate_update` BEFORE UPDATE ON `booking` FOR EACH ROW BEGIN IF EXISTS (SELECT date_IN, date_OUT FROM booking WHERE date_IN <= NEW.date_IN AND date_OUT > NEW.date_OUT) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An error occurred'; END IF; END $$ DELIMITER ; insert into booking (room, date_IN, date_OUT) VALUES (101, '2016-12-29', '2017-01-01'); insert into booking (room, date_IN, date_OUT) VALUES (101, '2017-01-01', '2017-01-04'); // Should fail to insert insert into booking (room, date_IN, date_OUT) VALUES (101, '2017-01-02', '2017-01-02'); 。然后检查要插入或更新的新日期是否在另一个条目的date_IN和date_OUT之间。

一个例子是

type Vehicle   struct {
    Id          bson.ObjectId `bson:"_vid,omitempty"`
    Brand           string
    Category        string  
    CategorySubject     string
    MakeYear        string
    RegistrationNumber  string
    Model           string
    Price           string
}
func (this *Vehicle)AddToDB(emailId1 string)  {
    sess, db := GetDatabase()
    defer sess.Close()
    c := db.C("user")
    //newId :=Vehicle{}
    /*colQuerier := bson.M{"email": person.Email}
    change := bson.M{"$set": bson.M{"profile" : imgName}}
    err = c.Update(colQuerier, change)*/
    colQuerier := bson.M{"email": emailId1}
    change := bson.M{"$push": bson.M{"myvehicle" : &this}}
    err := c.Update(colQuerier, change)
    if err != nil {
        fmt.Println("not inserted") 
    }
}