如何将CASCADE添加到已创建的外键中

时间:2014-01-07 16:28:54

标签: mysql

雇主:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(255)     | NO   | PRI | NULL    | auto_increment |
| corp     | varchar(255) | NO   |     | NULL    |                |
| type     | char(1)      | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

员工:

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(255)     | NO   | PRI | NULL    | auto_increment |
| name         | varchar(255) | NO   |     | NULL    |                |
| employer_id  | int(255)     | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

employer_id引用表雇主字段ID。

如何更改表以添加级联?

1 个答案:

答案 0 :(得分:2)

我们走了!

没有办法简单地改变,你必须简单地删除并重新创建

--To  Drop Foreign key     
ALTER TABLE [table_name] DROP FOREIGN KEY [foreign key];

--To Alter
ALTER TABLE [table_name]
ADD CONSTRAINT [foreign key name from above]
FOREIGN KEY (`[column_name]`) REFERENCES `[other_table]` (`[column_name]`)
ON DELETE CASCADE;