標籤:主表 python query mysql外鍵 mysql for size alter tab
定義
外鍵:如果一個表的某個欄位指向另一個表的主鍵,就稱之為外鍵。被指向的表,稱之為主表,也叫父表,那麼另一個表就是從表,也叫子表
#先建立兩個表
mysql> create table author_table( -> author_id int(4) not null primary key auto_increment, -> author_name char(20) not null);Query OK, 0 rows affected (0.02 sec)
mysql> create table article_table( -> article_id int(4) not null primary key auto_increment, -> article_title char(20) not null, -> author_id int(4) not null, -> foreign key(author_id) references author_table(author_id)); #這一步使得article_table中的author_id欄位成為外鍵Query OK, 0 rows affected (0.02 sec)
#添加資料
mysql> insert into author_table values -> (1,‘zhao‘), -> (2,‘qian‘), -> (3,‘sun‘), -> (4,‘li‘);Query OK, 4 rows affected (0.01 sec)Records: 4 Duplicates: 0 Warnings: 0
mysql> insert into article_table values -> (1001,‘c++‘,1), -> (1002,‘java‘,1), -> (1003,‘python‘,2), -> (1004,‘mysql‘,3), -> (1005,‘jacascript‘,4);Query OK, 5 rows affected (0.00 sec)Records: 5 Duplicates: 0 Warnings: 0
#子表和附表之間的約束
0 article_table中不能添加author_id為5的記錄;
1 author_table中不能刪除author_id為4的記錄,因為子表中還有作者4的文章
#刪除外鍵約束
mysql> alter table article_table drop foreign key article_table_ibfk_1;Query OK, 0 rows affected (0.02 sec)Records: 0 Duplicates: 0 Warnings: 0
#級聯操作
#添加外鍵
mysql> alter table article_table -> add foreign key fk_id(author_id) #這裡fk_id可以自己指定 -> references author_table(author_id) -> on delete cascade #cascade表示關聯操作。子表會依賴父表中的資料關聯刪除或更新 -> on update cascade; Query OK, 5 rows affected (0.02 sec)Records: 5 Duplicates: 0 Warnings: 0
#set null關鍵字
set null,表示子表資料不指向父表任何記錄。當不加set null和cascade時,預設為restrict(拒絕主表的相關操作),所以開始主表無法刪除資料
程式媛計劃——mysql外鍵