以下是語(yǔ)法 –
alter table yourSecondTableName add constraint `yourConstraintName` foreign key(`yourSecondTableNamePrimaryKey`) references yourFirstTableName(yourFirstTablePrimaryKeyColumnName);
登錄后復(fù)制
為了理解上述語(yǔ)法,讓我們首先創(chuàng)建一個(gè)表 –
mysql> create table demo65 −> ( −> id int not null primary key, −> name varchar(20) −> ); Query OK, 0 rows affected (0.57 sec)
登錄后復(fù)制
以下是創(chuàng)建第二個(gè)表的查詢(xún) –
mysql> create table demo66 −> ( −> user_id int not null primary key, −> address varchar(200) −> ); Query OK, 0 rows affected (1.80 sec)
登錄后復(fù)制
以下是將主鍵引用為外鍵的查詢(xún) –
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
登錄后復(fù)制
讓我們使用 SHOW CREATE TABLE 命令檢查表的整體描述。以下是查詢(xún) –
mysql> show create table demo66;
登錄后復(fù)制
這將產(chǎn)生以下輸出 –
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | 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)
登錄后復(fù)制
以上就是如何將主鍵作為外部引用到MySQL中的各種表?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!