1.設(shè)置表主鍵
主鍵必須唯一鲸睛,主鍵值非空荠割;主鍵可以是單一字段玷或,也可以是多字段組合。
1)單字段主鍵
語(yǔ)法格式:
屬性名 數(shù)據(jù)類型 primary key
實(shí)例:
create table example1(stu_id int primary key, stu_name varchar(20))
stu_id 為主鍵
2)多字段主鍵
在屬性定義完后統(tǒng)一設(shè)置主鍵
語(yǔ)法格式:
primary key( 屬性名1, 屬性名2, ... ,屬性名n)
實(shí)例:
create table example2(stu_id int, course_id int, name varchar(20), primary key (stu_id, course_id) )
stu_id , course_id 都為主鍵毕莱,兩者組合可以確定唯一記錄
2.設(shè)置表的外鍵
作用是建立該表與其父表的關(guān)聯(lián)關(guān)系器贩。
語(yǔ)法格式:
constraint 外鍵別名 foreign key(屬性 1.1,屬性1.2 ... 屬性1.n)
references 表名(屬性 2.1朋截,屬性2.2 ... 屬性2.n)
"外鍵別名"是為外鍵的代號(hào)蛹稍,屬性 1參數(shù)列表是子表設(shè)置的外鍵,表名是父表表名部服,屬性2參數(shù)列表是父表主鍵
實(shí)例:
create table example3(id int primary key, stu_id int, course_id int, constraint c_fk foreign key(stu_id, course_id) references example2(stu_id,course_id))
3.設(shè)置表的非空約束
非空約束即字段值不能為空
語(yǔ)法格式:
屬性名 數(shù)據(jù)類型 not null
實(shí)例:
create table example4( id int not null primary key, name varchar(20) not null)
4.設(shè)置表的唯一性約束
即表記錄中該字段值不能重復(fù)唆姐。
語(yǔ)法格式:
屬性名 數(shù)據(jù)類型 unique
實(shí)例:
create table example5(id int , stu_id int unique)
5.設(shè)置表的屬性值自動(dòng)增加
一個(gè)表只能有一個(gè)字段試用auto_increment約束,且該字段必須為主鍵的一部分廓八。此字段可以是任何整數(shù)類型厦酬。默認(rèn)從1開始自增胆描。
語(yǔ)法格式:
屬性名 數(shù)據(jù)類型 auto_increment
實(shí)例:
create table example6(id int primary key auto_increment, stu_id int unique)
6.設(shè)置表的屬性默認(rèn)值
如果創(chuàng)建一條記錄時(shí)如果沒有輸入此字段值,則會(huì)為該字段插入默認(rèn)值
語(yǔ)法格式:
屬性名 數(shù)據(jù)類型 default 默認(rèn)值
實(shí)例:
create table example7(id int , stu_id, name carchar(20) default 'wu_ming', computer float default 0 )