MySQL限制关系表与FIFO

时间:2017-11-12 08:50:48

标签: mysql many-to-many fifo

目前正致力于社交网站的MySQL结构。

我有一个要求:一个用户最多只能有5个朋友,当添加第6个时,它会删除最旧的一个(FIFO),我不完全确定解决这个问题的最佳方法是什么。

在我的后端代码中,我还在添加用户时添加了一个约束,以便user1_id< user2_id。

以下是相关表格:

CREATE TABLE friendships (
user1_id INT,
user2_id INT,
date_added DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user1_id)
    REFERENCES users (id)
    ON DELETE CASCADE,
FOREIGN KEY (user2_id)
    REFERENCES users (id)
    ON DELETE CASCADE
);

CREATE UNIQUE index single on friendships (user1_id, user2_id);

我考虑使用触发器并写下:

CREATE TRIGGER inFriendships 
BEFORE INSERT ON friendships
FOR EACH ROW
BEGIN
  DECLARE current_amount_user1 INT DEFAULT 0;
  DECLARE current_amount_user2 INT DEFAULT 0;
  SET current_amount_user1 = ( SELECT COUNT(*) FROM friendships WHERE (user1_id = NEW.user1_id OR user2_id = NEW.user1_id) );
  IF current_amount_user1 = 5
    THEN 
      DELETE FROM friendships WHERE date_added IS NOT NULL AND (user1_id = NEW.user1_id OR user2_id = NEW.user1_id) order by date_added desc LIMIT 1;
  END IF;
  SET current_amount_user2 = ( SELECT COUNT(*) FROM friendships WHERE (user1_id = NEW.user2_id OR user2_id = NEW.user2_id) );
  IF current_amount_user2 = 5
    THEN 
      DELETE FROM friendships WHERE date_added IS NOT NULL AND (user1_id = NEW.user2_id OR user2_id = NEW.user2_id) order by date_added desc LIMIT 1;
  END IF;
END;

但我遇到了死锁的问题,现在我正试图找到一个不同的解决方案。

所有解决方案和想法都欢迎使用SQL和后端伪代码。

1 个答案:

答案 0 :(得分:0)

(user1_id = NEW.user2_id OR user2_id = NEW.user2_id)意味着用户最多只能与5个人联系。应该有一种感觉; user1_id应该是父用户的ID,user2_id应该是子用户。 考虑到这一点,以获得用户的朋友数量:

SELECT user1_id, user2_id, date_updated from friendships where user1_id=NEW.user1_id;

您可以允许数据插入友谊,然后在插入后运行触发器,以便在朋友数量超过5的情况下删除最老的朋友。