外鍵約束: foreign key
保持數據的完整性 一致性。 實現一對一 或一對多的關系
外鍵約束的要求:
1 父表與子表必須使用相同的存儲引擎 而且禁止使用臨時表
2 數據表的存儲引擎只能為 InnoDB;
3 外鍵列和參照列必須具有相似的數據類型 其中數字長度或是否有符號位必須相同 ,而字符的長度可以不同
4 外鍵列和參照列必須創建索引, 如果外鍵列不存在索引的話 mysql 將自動創建索引
編輯數據表的默認存儲引擎 :
mysql 配置文件: 在my.ini 中 default-storage-engine = INNODB;
外鍵約束的參照操作
1 cascade 從父表刪除或更新且自動刪除或更新子表中匹配的行
2 set null 從父表刪除或更新行 并且設置字表中的外鍵列為null, 如果使用該選項 必須保證子表列沒有只定not null
3 restrict 拒絕對父表的刪除或更新操作
4 not action 標準sql的關鍵字 在mysql中 與 restrict相同
修改數據表:
添加單列 alter table user1 add age tinyint unsigned not null default 10;
添加的列 至于 某個字段的后面 alter table user1 add pwd varchar(10) not null after username;
添加多列 只能順序添加
刪除列:
alter table users1 drop name;
刪除多列
alter table users1 drop name,drop name;
添加主鍵約束:
alter table users2 add constraint pk_users2_id primary key (id); constraint 可以不寫
添加唯一約束
alter table users2 add unique (username);
添加外鍵約束
alter table users2 add foreign key (pid) references pro (id);
添加刪除默認約束
alter table users2 alter age set default 10;
alter table users2 alter age drop default;
刪除主鍵約束
alter table users2 drop primary key;
刪除唯一約束:
alter table users2 drop index username;
刪除外鍵約束:
alter table users2 drop foreign key 外鍵約束名字 ;
修改列定義
修改列位置: alter table users modify id smallint unsigned not null first;
修改字段類型 : alter table users modify id tinyint unsigned not null ;
修改列名稱: alter table users change pid p_id tinyint unsigned not null;
修改數據表名: alter table users rename users3;
rename table users3 to users2;