
以下是語法-
1 2 3 4 | alter table yourSecondTableName
add constraint `yourConstraintName`
foreign key(`yourSecondTableNamePrimaryKey`)
references yourFirstTableName(yourFirstTablePrimaryKeyColumnName);
|
登入後複製
為了理解上述語法,讓我們先建立一個表格-
1 2 3 4 5 6 | mysql> create table demo65
−> (
−> id int not null primary key,
−> name varchar(20)
−> );
Query OK, 0 rows affected (0.57 sec)
|
登入後複製
以下是建立第二個表的查詢-
1 2 3 4 5 6 | mysql> create table demo66
−> (
−> user_id int not null primary key,
−> address varchar(200)
−> );
Query OK, 0 rows affected (1.80 sec)
|
登入後複製
以下是將主鍵引用為外鍵的查詢-
1 2 3 4 5 6 | mysql> alter table demo66
−> add constraint `id_fk`
−> foreign key(`user_id`)
−> references demo65(id);
Query OK, 0 rows affected (3.76 sec)
Records: 0 Duplicates: 0 Warnings: 0
|
登入後複製
讓我們使用SHOW CREATE TABLE 命令檢查表的整體描述。以下是查詢 -
1 | mysql> show create table demo66;
|
登入後複製
這將產生以下輸出 -
1 2 3 4 5 6 7 8 9 10 | +--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table +--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| demo66 | CREATE TABLE `demo66` (
`user_id` int NOT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`user_id`),
CONSTRAINT `id_fk` FOREIGN KEY (`user_id`) REFERENCES `demo65` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
|
登入後複製
以上是如何將主鍵作為外部引用到MySQL中的各種表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!