mysql筆記--表級別的約束

表級別的約束

1. 主鍵約束----primary key

主鍵:表中一個列或者多個列的組合,要求該列的數據唯一

單字段主鍵:字段名 數據類型 屬性 primary key

多字段主鍵:primary key (字段1,字段2

主鍵列的值不能爲空!!!

 

例子:創建一張員工表tb_emp1,以id爲主鍵

    create table tb_emp1(id int primary key,name varchar(25),deptid int,salary float);             創建一張員工表tb_emp1,以idname爲組合主鍵

    create table tb_emp3(id int,name varchar(25),deptid int,salary float,primary key(id,name));


2. 自動增長----auto_incerment

只作用於主鍵,是數值型的自動增長

 例子:

    create table tb_emp4(id int primary key auto_increment,name varchar(25),deptid int,

salary float);


3. 非空約束----not null

Create 表名(列名 類型 not null

 

4. 默認值約束----default

Create 表名(列名 類型 not null default 數值)

 

    create table tb_emp6(id int primary key auto_increment,name varchar(25) not null,

deptid int not null default 1,salary float not null default 5000);


5. 外鍵----foreign key

外鍵主要用來將兩個表的數據進行連接

create 表名(列名 類型 屬性,constraint 外鍵名稱 foreign key(列名)

references 另一個表名(列名));

注意:建立外鍵連接的兩個字段的類型、屬性要一致!!!

 

    例子:建立部門表 tb_dept7、員工表tb_emp7,將兩張表的deptid建立外鍵約束

    create table tb_dept7(id int primary key,name varchar(20));

注:部門表要先插入數據才能建立員工表

    create table tb_emp7(id int primary key auto_increment,name varchar(25) not null,

deptid int not null default 1,salary float not null default 5000,constraint fk_emp7_dept7 foreign key(deptid) references tb_dept7(id));

  

    刪除外鍵:因爲可以有多個外鍵,所以要有名稱

    要刪除建立外鍵連接的表數據時,要先解除外鍵連接

    alter table 表名drop foreign key 外鍵名稱;

            

         刪除主鍵:alter table 表名 drop primary key;

        如果主鍵字段是自增時,不能直接刪除,要先改定義把自增刪除!


 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章