Pergunta

In a database, I have a username table and I have jurisdiction table. I also have a intermediate table to assign a user to one or more jurisdictions.

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 |
    +--------+-------+

I want to make it where if I delete a parent table row, the intermediate table with the corresponding foreign key would be deleted automatically. I made the intermedieate table with:

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);

But when I delete something from the parent table....like a state name row from table jurisidictions.jurisdiction...the userID and jurID row does not get deleted from the intermediate table user_jurisdiction automatically. From what I can see, I made the DELETE ON CASCADE correct on each foreign key. Why aren't the corresponding rows with the foreign keys deleting in the intermediate table when the parent table row get's deleted?

Foi útil?

Solução

The most likely reason is that you're using the MyISAM engine instead of the INNODB engine. The MyISAM engine parses foreign key constraints, but it doesn't enforce them.

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 is the default storage engine for MySQL starting with version 5.5. MyISAM was the default before that.

Get in the habit of posting SQL DDL instead of (or along with) a description of the tables. DDL is a lot more accurate than a description.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top