【问题标题】:How to add a integrity check on mySQL Workbench如何在 mySQL Workbench 上添加完整性检查
【发布时间】:2021-03-13 13:47:13
【问题描述】:

我是 mySQL 的新手,我想在我的数据库中添加完整性检查(或约束?对不起,我是意大利人)。 让我解释一下:我有两张桌子

Workshop (location, numPlaces, numOperations)
Operation (idoperation, workLocation, ...)

numPlaces 表示车间可以承受的最大操作数。我创建了一个触发器,每次我在 Operation 中插入新记录时,该特定位置的 Workshop 的 numOperations 都会增加 1。

现在我想做的是:当numOperations = numPlaces 时,如果我尝试向Operation 插入新记录,系统必须告诉我不能。基本上不可能numOperations > numPlaces

有没有办法做到这一点?抱歉,如果我不能提供代码,但我真的不知道应该去哪里创建这些类型的 CHECKS。希望你能帮助我!

【问题讨论】:

  • chekc 只能在 mysql 8 中工作,所以你使用的是哪个版本,但这只适用于一个表
  • 我使用的是 mySQL Workbench 8.0
  • 检查约束只在表中起作用,所以你必须为此使用触发器

标签: mysql constraints workbench integrity


【解决方案1】:

为此,您必须为车间设置正确数量的位置。 你应该有一个例程,减少操作次数,这样你就可以在一个车间进入新的操作

CREATE TABLE Workshop 
(location Text, numPlaces int , numOperations int
)
INSERT INTO Workshop VALUES ('A',9,8)
CREATE TABLE Operation (idoperation int, workLocation Text)
CREATE TRIGGER before_Operation_insert
BEFORE INSERT
ON Operation FOR EACH ROW
BEGIN
    DECLARE Placescount_ INT;
    DECLARE Operationscount_ INT;
    
    SELECT numPlaces, numOperations
    INTO Placescount_,Operationscount_
    FROM Workshop WHERE location = NEW.workLocation;
    
    IF Placescount_ < Operationscount_ THEN
        UPDATE Workshop
        SET numOperations = numOperations + 1  WHERE location=new.workLocation ;
    ELSE
        SIGNAL SQLSTATE '45000'
      SET MESSAGE_TEXT = 'Maximum Number of Operarations reached in location ';
    END IF; 

END
INSERT INTO Operation VALUES (1,'A')
位置达到的最大操作次数

db小提琴here

【讨论】:

  • 谢谢!!这行得通!起初它给了我 ERROR 1175: 1175: You are using safe update mode and you try to update a table without a WHERE that uses a KEY column,然后我在 SET numOperations = numOperations+1; 下添加了一个 WHERE location=new.workLocation;它工作得很好。不知道我可以使用仍然触发器来报告错误!
猜你喜欢
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
相关资源
最近更新 更多