約束和修改資料表

2021-07-23 12:55:40 字數 3059 閱讀 9350

外來鍵約束(foreign key):

作用:保證資料的一致性、完整性,實現一對一或一對多關係

要求:

1.父表和字表必須使用相同的儲存引擎,禁止使用臨時表

2.資料表的儲存引擎只能是innodb

3.外來鍵列和參照列必須有相似的資料型別,其中數字的長度和符號位必須相同,字元的長度可以不同

4.外來鍵列和參照列必須建立索引,參照列沒有索引,mysql會自動建立索引

# my.ini(配置檔案)

default-storage-engine=innodb

1.cascade:從父表刪除或更新且自動刪除或更新子表中匹配的行

2.set null:從父表刪除或更新行,並設定子表中的外來鍵列為null,如果使用該選項,必須保證子表列沒有指定not null

3.restrict:拒絕對父表的刪除和更新操作

4.no action:標準的sql關鍵字,在mysql中和restrict相同

表級和列級約束:

乙個資料列建立的約束,稱為列級約束(常用)

多個資料列建立的約束,稱為表級約束

列級約束既可以在列定義時宣告,也可以在列定義後宣告,表級約束只能在列定以後宣告

not null和default只存在列級約束

alter

table tbl_name add [column] col_name column_definition [first|after col_name]

新增多列:

alter table tbl_name add [column]

(col_name column_definition,...)

區別

1.新增單列的時候列不需要新增小括號

2.新增單列的時候可以指定位置關係,多列只能在原資料表的下方

單列:

alter

table tbl_name drop [column] col_name

多列:

alter

table tbl_name drop [column], drop [column],....

也可以同時刪除一列並增加另一列,之間用逗號連線

新增主鍵約束:

alter

table tbl_name add [constraint [symbol]] primary

key [index_type] (index_col_name,....)

新增唯一約束:

alter

table tbl_name add [constraint [symbol]] unique [index|key] [index_name] [index_type] (index_col_name,....)

新增外來鍵約束:

alter

table tbl_name add [constraint [symbol]] foreign

key [index_name]

alter

table tbl_name alter [column] col_name

刪除主鍵約束:

alter

table tbl_name drop

primary

key

因為每個資料表有且只有乙個主鍵所以不用指定名稱

刪除唯一約束:

alter

table tbl_name drop index_name

顯示表中索引:

show indexes from tbl_name

刪除外來鍵約束:

alter

table tbl_name drop

foreign

key fk_symbol

修改列定義:

alter

table tbl_name modify [column] col_name column_definition [fitst|after col_name]

注:由大型別改到小型別有可能會導致資料的丟失

修改列名稱(和定義):

alter

table tbl_name change [column] old_col_name new_col_name column_definition [first|after col_name]

修改資料表名稱:

方法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]...

約束以及修改資料表

約束 1,約束保證資料的完整行和一致性。2,約束分為表級約束和列級約束。3,約束型別包括 primary key 主鍵約束 unique key 唯一約束 default 預設約束 foreign key 外來鍵約束 外來鍵約束的要求 1,父表和子表必須使用相同的儲存引擎,而且禁止使用臨時表。2,資...

MySQL之約束 修改資料表

一 約束 約束保證資料的完整性和一致性 約束分為表級約束和列級約束。約束型別包括 not null 非空約束 primary key 主鍵約束 unique key 唯一約束 default 預設約束 forgign key 外來鍵約束 列級約束 對乙個資料列建立的約束,既可以在列定義時宣告,亦可以...

資料庫 筆記 定義資料表約束和修改資料表

修改資料表 總結在這裡只使用sql語句來進行 null not null約束 分別表示可以為空和不可以為空,語句如下 create table stu stu no nchar 11 constraint s con not null constraint 約束名 約束型別,其中約束名自己定義,中括...