MySQL插入 - 如何防止同一个表中的两个外来ID相同?

时间:2017-11-15 16:45:48

标签: mysql database

尝试创建一个论坛数据库,用户可以在其中关注其他用户,反之亦然。为此我有两张桌子" user"和" follow_user"。

这很好用:

INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(13,14); INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(13,15); INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(14,13); INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(14,15); INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(15,13); INSERT INTO forumfollow_userfollower_idbeing_followed_id)VALUES(15,14);

问题:用户不应该自己关注(目前我的数据库允许):

INSERT INTO forumfollow_userfollower_idbeing_followed_id)价值观(13,13);

CREATE TABLE `forum`.`user` (
`user_id` SMALLINT(5) NOT NULL,
`user_name` VARCHAR(45) NOT NULL,
`user_email` VARCHAR(65) NOT NULL,
`user_signature` VARCHAR(240) NULL,
`user_created` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`user_updated` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`));


CREATE TABLE `follow_user` (
`follower_id` smallint(5) NOT NULL,
`being_followed_id` smallint(5) NOT NULL,
PRIMARY KEY (`follower_id`,`being_followed_id`),
UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
KEY `follower_id_fk_idx` (`follower_id`),
KEY `being_followed_id_fk_idx` (`being_followed_id`),
CONSTRAINT `being_followed_id_fk` 
FOREIGN KEY (`being_followed_id`)
REFERENCES `user` (`user_id`) 
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`) 
ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';

1 个答案:

答案 0 :(得分:0)

您可以在插入之前使用触发器执行,以确保两列不具有相同的值。

CREATE TABLE `follow_user` (
    `follower_id` smallint(5) NOT NULL,
    `being_followed_id` smallint(5) NOT NULL,
    PRIMARY KEY (`follower_id`,`being_followed_id`),
    UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
    KEY `follower_id_fk_idx` (`follower_id`),
    KEY `being_followed_id_fk_idx` (`being_followed_id`),
    CONSTRAINT `being_followed_id_fk` 
    FOREIGN KEY (`being_followed_id`)
    REFERENCES `user` (`user_id`) 
    ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`) 
    ON DELETE NO ACTION ON UPDATE NO ACTION
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';

CREATE TRIGGER follow_user_before_insert 
BEFORE INSERT ON follow_user FOR EACH ROW
BEGIN
    IF NEW.follower_id = NEW.being_followed_id
    THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Cannot add or update row: follower_id must be different from being_followed_id'
    END IF
END
/

但是,正如@ADyson在评论中提到的那样,在应用程序级别上做一个简单的if else语句可能更简单。

if(followerId != beingFollowedId) {
    // insert
}
else {
    // throw exception or return error code/message
}