如何為現有 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)
廣告