如何向现有 MySQL 表的字段添加 FOREIGN KEY 约束?
mysqlmysqli database
我们可以借助 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)