我们如何向现有 MySQL 表中的字段添加 FOREIGN KEY 约束?


借助 ALTER TABLE 语句,我们可向现有 MySQL 表的一列中添加 FOREIGN KEY 约束。

语法

ALTER TABLE table_name ADD FOREIGN KEY (colum_name) REFERENCES table having Primary Key(column_name);

示例

假设我们希望对表‘Orders1’添加 FOREIGN KEY 约束,该约束将引用表‘Customer’,该表中包含列‘Cust_Id’作为主关键字。可借助以下查询来实现 −

mysql> Alter table orders1 add FOREIGN KEY(Cust_id) REFERENCES Customer(Cust_id);
Query OK, 0 rows affected (0.21 sec)
Records: 0  Duplicates: 0  Warnings: 0  

mysql> Describe ORDERS1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.05 sec)

更新于: 30-Jul-2019

2K+ 浏览量

开启你的 职业生涯

根据完成课程的情况获得认证

开始
广告
© . All rights reserved.