一、約束
約束保證資料的完整性和一致性;約束分為表級約束和列級約束。約束型別包括:not null(非空約束)、primary key(主鍵約束)、unique key(唯一約束)、default(預設約束)、forgign key(外來鍵約束)。
列級約束:對乙個資料列建立的約束,既可以在列定義時宣告,亦可以在列定義後宣告
表級約束:對多個資料列建立的約束,只能在列定義後宣告
二、foregin key(外來鍵約束)
保持資料一致性,完整性;實現一對一或一對多的關係;
外來鍵約束的要求:
1.父表和子表必須使用相同的儲存引擎,而且禁止使用臨時表;
2.資料表的儲存引擎只能為innodb;
3.外來鍵列和參照列必須具有相似的資料型別;其中數字的長度或是否有符號位必須相同;而字元的長度則可以不同;
4.外來鍵列和參照列必須建立索引。如果參照列不存在索引的話,mysql不會自動建立索引。但如果參照列為主鍵的話,則會自動建立索引。
主鍵在建立的同時會自動建立索引,所以參照列其實已經有了索引。
而外鍵列上沒有建立索引,mysql則會自動建立索引。
三、編輯資料表的預設儲存引擎
mysql配置檔案:default-storage-engine=innodb(windos下在my.ini中,linux下在/etc/my.cnf)
四、外來鍵約束的參照操作
1.cascade:從父表刪除或更新且自動刪除或更新子表中匹配的行;
2.set null:從父表刪除或更新行,並設定子表中的外來鍵列為null。如果使用該選項,必須保證子列表沒有指定not null
3.restrict:拒絕對父表的刪除或更新操作。
4.no action:標準sql的關鍵字,在mysql中與restrict相同
五、資料表列處理
1.新增單列
alter table tbl_name add [column] col_name colume_definition [first| after col_name]
eg:alter table user add age tinyint unsiened not null first(新增到所有列的前端)
eg:alter table user add passwd varchar(20) not null after id(新增到id列的後邊)
2.新增多列:
alter table tbl_name add [column] (col_name column_definition,......)(不能指定位置,預設新增在後)
3.刪除列
alter table tbl_name drop [column] col_name
4.新增主鍵約束(在表沒有主鍵的時候)
alter table tbl_name add [consatraint symbol]] primary key [index_type] (index_col_name,..)
eg:alter table users add pyimary key (id);
5.刪除主鍵約束
alter table tbl_name drop primary key
6.新增唯一約束
alter table tbl_name add [consatraint symbol]] unique [index|key] [index_name] [index_type] (index_col_name,..)
可以新增多個而主鍵只能新增乙個
eg:alter table users add unique key (username);
7.刪除唯一約束
alter table tbl_name drop index_name
index_name 通過命令:show indexes from users\g;查詢
8.新增外來鍵約束
alter table tbl_name add [consatraint symbol]] foreign key [index_name] (index_col_name,..) reference_definition
eg:alter table users add foreign key (pid) references provinces (id);
9.刪除外來鍵約束
alter table tbl_name drop foreign key fk_symbol
fk_symbol:通過命令:show create table users(資料表名字);來查詢,由系統給的
10.新增/刪除預設約束
alter table tbl_name alter [column] col_name
eg:alter table users alter age set 15;
五、修改資料表
1.修改列定義
alter table tbl_name modify [column] col_name column_definition [first|after col _name]
修改型別的時候,如果大型別修改為小型別,有可能會造成資料丟失
eg:alter table users modify id smallint unsigned not null first;
2.修改列名稱
alter table tbl_name change [column] old_col_name new_col_name column _definition [first|after col_name]
3.資料表更名
1):alter table tbl_name rename [to|as] new_tbl_name
2):rename table tbl_name to new_tbl_name [,tbl_name2 to new_tbl_name2] ...
Mysql值之約束以及修改資料表
unsigned 這裡約束的意思是沒符號,不能為負數,只能是整數 外來鍵約束的參照操作 由上圖中的指令,on delete是在執行刪除指令,當我們重新建立一張表關聯父表,然後為他們新增資料,但是當我們刪除父表中的資料後,子表中的資料也會隨著父表的刪除而刪除,這裡只是展示了刪除,同時更新也是一樣的 表...
約束和修改資料表
外來鍵約束 foreign key 作用 保證資料的一致性 完整性,實現一對一或一對多關係 要求 1.父表和字表必須使用相同的儲存引擎,禁止使用臨時表 2.資料表的儲存引擎只能是innodb 3.外來鍵列和參照列必須有相似的資料型別,其中數字的長度和符號位必須相同,字元的長度可以不同 4.外來鍵列和...
約束以及修改資料表
約束 1,約束保證資料的完整行和一致性。2,約束分為表級約束和列級約束。3,約束型別包括 primary key 主鍵約束 unique key 唯一約束 default 預設約束 foreign key 外來鍵約束 外來鍵約束的要求 1,父表和子表必須使用相同的儲存引擎,而且禁止使用臨時表。2,資...