MySQL筆記 16 約束

2021-10-24 19:00:56 字數 3879 閱讀 1024

列級的外來鍵約束沒有效果,表級的非空和預設約束不支援

create

table stu_info (

id int

primary

key,

stu_name varchar(20

)not

null

, gender char(1

)check

(gender =

'男'or gender =

'女')

, seat int

unique

, age int

default18,

major_id int

references major (id));

create

table major (

id int

primary

key,

major_name varchar(20

)not

null

);

create

table info (

id int

, stu_name varchar(20

),gender char(1

),seat int

, age int

, major_id int

,-- constraint pk可以去掉

constraint pk primary

key(id)

,constraint uq unique

(seat)

,constraint ck check

(gender =

'男'or gender =

'女')

,constraint fk foreign

key(major_id)

references major (id)

);

非空約束

alter

table

`stu_info`

modify

column

`stu_name`

varchar(20

)not

null

;

預設約束

alter

table

`stu_info`

modify

column

`age`

intdefault

18;

主鍵約束

alter

table

`stu_info`

modify

column

`id`

intprimary

key;

alter

table

`stu_info`

addprimary

key(id)

;

唯一鍵約束

alter

table

`stu_info`

modify

column

`seat`

intunique

;alter

table

`stu_info`

addunique

(`seat`

);

外來鍵約束

alter

table

`stu_info`

addforeign

key(

`major_id`

)references major (id)

;

刪除非空約束

alter

table

`stu_info`

modify

column

`stu_name`

varchar(20

);

刪除預設約束

alter

table

`stu_info`

modify

column

`age`

int;

刪除主鍵約束

alter

table

`stu_info`

drop

primary

key;

刪除唯一鍵約束

-- 查詢出唯一鍵的key,再根據key進行刪除

show

index

from

`stu_info`

;alter

table

`stu_info`

drop

index seat ;

刪除外來鍵約束

alter

table

`stu_info`

drop

foreign

key major_id ;

保證唯一性

是否允許為空

乙個表中可以有幾個

是否允許組合(多個組成乙個)主鍵y

n至多有乙個

y(不推薦)唯一y

y可以有多個

y(不推薦)

設定級聯刪除(在刪除主表中的資料時,從表中引用了主表中相關資料的資料也會被刪除)

alter

table

`beauty`

addforeign

key(

`boyfriend_id`

)references

`boys`

(`id`)on

delete

cascade

;

設定級聯置空(在刪除主表中的資料時,從表中引用了主表中相關資料的資料會被置空)

alter

table

`beauty`

addforeign

key(

`boyfriend_id`

)references

`boys`

(`id`)on

delete

setnull

;

可以不用手動的插入值,系統提供預設的序列值

create

table au (

id int

primary

keyauto_increment

,`name`

varchar(20

));

alter

table

`au`

modify

column id int

primary

keyauto_increment

;

alter

table

`au`

modify

column id int

;

show variables like

'%auto_incre%'

;

可以設定變數的值來改變效果但一般不做修改,但mysql不支援修改 auto_increment_offset

set auto_increment_increment =

3;

MySQL學習筆記16 資料約束

一 設定主鍵 主鍵關鍵字 primary key 主鍵的選擇 通常不用業務資料作為主鍵,主鍵絕對不能重複,通常選擇id作為主鍵。設定語句 create table teacher2 id int primary key,name char 6 age int,birthday date,char 1...

MySQL約束筆記

mysql 檢視約束,新增約束,刪除約束 新增列,修改列,刪除列 檢視表的字段資訊 desc 表名 檢視表的所有資訊 show create table 表名 新增主鍵約束 alter table 表名 add constraint 主鍵 形如 pk 表名 primary key 表名 主鍵字段 如...

MySQL筆記(二)約束

1.1主鍵 主鍵 primary key 用於約束表中的一行,作為這一行的唯一識別符號 在一張表中通過主鍵就能準確定位到一行。主鍵不能有重複並且不能為空。一般可以這樣定義主鍵 create table 表名 列名 資料型別 primary key 或者create table 表名 列名 資料型別 ...