如何为现有 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)
广告