使用MySQL中的触发器和约束限制记录数

时间:2012-03-08 16:51:16

标签: mysql triggers constraints

我有一个名为BFFs的表,它存储了userID和最好朋友的用户ID,我想限制该表为每个不同的用户准备好3个最好的朋友。

我的意思是表结构是:

BFFs(userID, userID)

和记录是:

(3286, 1212)
(3286, 4545)
(3286, 7878)

在这种情况下,如果不允许ID为3286的用户拥有新记录,例如(3286,xyzt)。

我写了这个触发器,但我不确定:

CREATE TRIGGER BFFControl
BEFORE INSERT ON BFFs
FOR EACH ROW
DECLARE
    numberOfBFFs INTEGER;
    max_BFFs INTEGER := 3;
BEGIN
    SELECT COUNT(*) INTO numberOfBFFs
    FROM BFFs
    WHERE sender =: NEW.sender

    IF :OLD.sender =: NEW.sender THEN
        RETURN;
    ELSE
        IF numberOfBFFs >= max_BFFs THEN
            RAISE_APPLICATION_ERROR(-20000, 'Users are allowed to have at most thre friends.');
        END IF;
    END IF;
END;
/

我应该如何通过断言或触发器在关系表上重新启动它?

谢谢

2 个答案:

答案 0 :(得分:2)

将另一列FriendNumber和一个外键约束添加到一个恰好有3行的参考表中:

CREATE TABLE Three
( friendNumber TINYINT NOT NULL 
, PRIMARY KEY (friendNumber)
) ;

INSERT INTO Three(friendNumber) 
  VALUES
    (1), (2), (3) ;

CREATE TABLE BFFs
( userID       INT NOT NULL 
, friendID     INT NOT NULL
, friendNumber TINYINT NOT NULL
, PRIMARY KEY (userID, friendID)
, UNIQUE (userID, friendNumber)
, FOREIGN KEY userID
    REFERENCES Person(userID)
, FOREIGN KEY friendID
    REFERENCES Person(userID) 

, FOREIGN KEY friendNumber           --- this ensures that a user can have
    REFERENCES Three(friendNumber)   --- max of 3 friends
) ;

然后你可以添加:

INSERT INTO BFFs 
  (userID, friendID, friendNumber)
VALUES
  (3286, 1212, 1) ,
  (3286, 4545, 2) ,
  (3286, 7878, 3) ;

或者像@gbn所建议的那样(所以列是自动填充的):

INSERT INTO BFFs 
    (userID, friendID, friendNumber)
  SELECT 
       3286 AS userID
     , 8989 AS friendID
     , COALESCE(
         ( SELECT MIN(Three.friendNumber)
           FROM Three 
             LEFT JOIN BFFs AS b  
               ON  b.friendNumber = Three.friendNumber
               AND b.userID = 3286
           WHERE b.friendNumber IS NULL
         ), 4
       ) AS friendNumber
  FROM dual

答案 1 :(得分:1)

除了超立方体的答案(利用DRI来强制执行您的规则),您还可以使用MIN LEFT JOIN从每个用户ID的三个表中获取1,2或3中的下一个