我有两个表:用户和管理员。
+-------------------------+
| TABLE : user
+-------------------------+
| id: PRIMARY_KEY
| username
| password
+-------------------------+
+-------------------------+
| TABLE: admin
+-------------------------+
| user_id: FOREIGN_KEY
| e-mail
+-------------------------+
管理员也是用户,因此,两个表在1:1的关系中是一起的。当从User表中删除一行时,它也会从表Admin中删除(在admin.user_id设置关系ON DELETE CASCADE),但如果我从表Admin中删除一行怎么办?然后它不会从User表中删除,这会使数据库中的混乱。这有什么解决方案吗?如何在双方制定实现?
答案 0 :(得分:1)
将类似的外键添加到admin
表 -
ALTER TABLE user
ADD CONSTRAINT FK_user_admin_user_id FOREIGN KEY (id)
REFERENCES admin(user_id) ON DELETE CASCADE ON UPDATE RESTRICT;
现在,您可以从user
或admin
表中删除行,并删除相关记录。
使用 FOREIGN_KEY_CHECKS 变量添加新记录,例如 -
SET FOREIGN_KEY_CHECKS = 0;
INSERT INTO user(id) VALUES(1);
INSERT INTO admin(user_id) VALUES(1);
SET FOREIGN_KEY_CHECKS = 1;
输出的完整示例 -
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(255) DEFAULT NULL,
password varchar(255) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_user_admin_user_id FOREIGN KEY (id)
REFERENCES admin (user_id) ON DELETE CASCADE ON UPDATE RESTRICT
)
ENGINE = INNODB;
CREATE TABLE admin (
user_id int(11) NOT NULL AUTO_INCREMENT,
`e-mail` varchar(255) DEFAULT NULL,
PRIMARY KEY (user_id),
CONSTRAINT FK_admin_user_id FOREIGN KEY (user_id)
REFERENCES user (id) ON DELETE CASCADE ON UPDATE RESTRICT
)
ENGINE = INNODB;
SET FOREIGN_KEY_CHECKS = 0;
INSERT INTO user(id) VALUES(1);
INSERT INTO user(id) VALUES(2);
INSERT INTO user(id) VALUES(3);
INSERT INTO admin(user_id) VALUES(1);
INSERT INTO admin(user_id) VALUES(2);
INSERT INTO admin(user_id) VALUES(3);
SET FOREIGN_KEY_CHECKS = 1;
DELETE FROM user WHERE id = 1;
DELETE FROM admin WHERE user_id = 2;
SELECT * FROM user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 3 | NULL | NULL |
+----+----------+----------+
SELECT * FROM admin;
+---------+--------+
| user_id | e-mail |
+---------+--------+
| 3 | NULL |
+---------+--------+