我们可以借助 ALTER TABLE 语句向现有 MySQL 表的列添加 FOREIGN KEY 约束。
语法
ALTER TABLE table_name ADD FOREIGN KEY (colum_name) REFERENCES table with Primary Key(column_name);
示例
假设我们要在表“Orders1”上添加一个外键约束,引用表“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)