1

在数据库中,我有一个用户名表,并且我有权限表。我也有一个中间表来分配一个用户到一个或多个司法管辖区。在删除父项时,在外键行上不删除Mysql'Cascade On Delete'

employee table 

userID (primary Key) 
firstName 
lastName 
records: 

+--------+-----------+----------+ 
| userID | firstName | lastName | 
+--------+-----------+----------+ 
|  6 | John  | Doe  | 
|  11 | lisa  | lopez | 
+--------+-----------+----------+ 
jurisdictions table 

jurId (Primary Key) 
region 
records: 

+-------+--------------+ 
| jurID | jurisdiction | 
+-------+--------------+ 
|  1 | California | 
|  2 | Texas  | 
|  3 | Washington | 
|  4 | South Dakota | 
|  5 | Alaska  | 
|  6 | Ohio   | 
+-------+--------------+ 
user_jurisdiction 

userID (Foriegn Key pointing to employees userID) 
jurID (Foriegn Key pointing to jurisdictions jurID) 
records: 

    +--------+-------+ 
    | userID | jurID | 
    +--------+-------+ 
    |  6 |  2 | 
    |  6 |  3 | 
    |  11 |  2 | 
    +--------+-------+ 

我想要,如果我删除父表行,与对应的外键中间表将被自动删除它在哪里。我做了intermedieate表:

CREATE TABLE user_jurisdiction(userID int NOT NULL, jurID int NOT NULL, FOREIGN KEY(userID) REFERENCES employee(userID) ON DELETE CASCADE, FOREIGN KEY (jurID) REFERENCES jurisdictions(jurID) ON DELETE CASCADE); 

但是当我删除父表的东西....就像从表jurisidictions.jurisdiction州名行...的用户ID和jurID行不会被删除,从中间表user_jurisdiction自动。从我所看到的情况来看,我在每个外键上对DELETE ON CASCADE进行了正确的设置。当父表行被删除时,为什么外键的相应行在中间表中删除?

回答

1

最可能的原因是您正在使用MyISAM引擎而不是INNODB引擎。 MyISAM引擎解析外键约束,但不强制执行它们。

CREATE TABLE user_jurisdiction(
    userID int NOT NULL, 
    jurID int NOT NULL, 
    FOREIGN KEY(userID) 
    REFERENCES employee(userID) ON DELETE CASCADE, 
    FOREIGN KEY (jurID) 
    REFERENCES jurisdictions(jurID) ON DELETE CASCADE 
) ENGINE=INNODB; 

INNODB是MySQL 5.5版本的默认存储引擎。 MyISAM在此之前是默认的。

养成使用SQL DDL而不是(或与之一起)对表进行描述的习惯。 DDL比描述更准确。