基于外键的唯一列约束

时间:2019-07-19 19:31:50

标签: mysql innodb

我正在尝试阻止将多种类型的规则应用于用户。我的表qrc:/qml/test.qml:25:9: QML Image: Cannot open: qrc:/resources/images/logo.svg通过rules连接到employee_rules。我想知道是否有一种方法可以根据不同表中的此外键列创建唯一条目。

例如:

ruleid

如上所示,rules ruleid typeid 1 2 2 0 3 1 4 0 employee_rules ruleid employeeid customerid 1 4 2 2 4 2 // Same typeid do not allow 4 4 2 // Same typeid do not allow 3 4 2 2 6 2 2 4 1 ruleid2是同一类型,所以我希望此条目产生错误。

1 个答案:

答案 0 :(得分:0)

正如@The Impaler在评论中提到的,我通过BEFORE INSERT触发器实现了这一点:

BEGIN
  DECLARE thisType INT;
  DECLARE numRows INT;
  SET thisType = (SELECT a.type FROM rules a WHERE a.ruleid = NEW.ruleid);
  SET numRows = (SELECT COUNT(a.ruleid) FROM employee_rules a LEFT JOIN rules b ON a.ruleid = b.ruleid WHERE a.employeeid = NEW.employeeid AND a.customerid = NEW.customerid AND b.type = thisType);
  IF numRows >= 1
  THEN
  SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Duplicate foreign column 'typeid'. (User-defined)";
  END IF;
END