2 修改表和新增約束

2021-08-14 16:54:39 字數 2160 閱讀 4850

目的格式舉例修

改表結構

1.修改列(字段)的資料型別

alter table 表名 modify(列名 資料型別);

alter

table

teachers

modify

(tid

varchar2(5

)) 2. 增加乙個列

alter table 表名 add(列名 資料型別);

alter

table

teachers

add(

klass

varchar2(10

)) 3. 給列改名字

alter table 表名 rename column 當前列名 to 新列名;

alter

table

teachers

rename

column

klass

toklasses

4. 刪除乙個列

alter table 表名 drop column 列名;

alter

table

teachers

drop

column

klasses

5. 表重新命名

alter table 當前表名 rename to 新錶名;

alter

table

teachers

rename

toteacher

6.給字段新增預設值

alter table 表名 modify 欄位名  default 預設值 ;

alter

table

teacher

modify

klass

default'1班

'

類別語法格式舉例添

加約束非空約束:

就是必須為某列提供值,空值是不存在的值,既不是數字0,也不是空字串,而是不存在、未知的情況。

alter table 表名 modify 欄位名 null;

alter table student modify studentid null;

主鍵約束

唯一地標識一條資料。在表中都要設定主鍵。主鍵不能是null值。在乙個表中,最多只能有乙個主鍵約束,主鍵約束可以由乙個列組成,也可以由兩個或兩個以上的列組成。主鍵約束同時也具有非空約束的特性。

alter table 表名

add constraint 約束名稱 primary key (欄位名);

alter table student

add constraint pk_id primary key (id);

外來鍵約束:

一張表的外來鍵需要指向另一張表的主鍵或者是唯一鍵。

至少需要兩張表。含有主鍵的表叫主表。外來鍵表叫從表。

alter table 表名

add constraint 約束名 foreign key(欄位名1)

references grade (欄位名1);

alter table student

add constraint fk_gradeid foreign key(gradeid)

references grade (gradeid);

檢查約束

alter table 表名

add constraint 約束名 check (條件);

alter table student

add constraint ck_*** check (*** in ('男','女'));

alter table student

add constraint ck_phone check (length(phone)=13);

唯一約束:強調所在的列不允許有相同的值,但是,它的定義要比主鍵約束弱,即它所在有列允許有空值。

alter table表名

add constraint 約束名 unique(欄位名);

alter table student

add constraint uq_phone unique(phone);

130 修改表時 新增 刪除 約束

新增約束 列級約束修改不能取名,表級約束修改才能取名 非空 alter table stuinfo modify column stunamne varchar 20 not null 預設約束 alter table stuinfo modify column age int default18 ...

MySQL 新增約束,修改約束,刪除約束

alter table 新增,修改,刪除表的列,約束等表的定義。檢視列 desc 表名 修改表名 alter table t book rename to bbb 新增列 alter table 表名 add column 列名 varchar 30 刪除列 alter table 表名 drop ...

myql 新增約束,修改約束,刪除約束

alter table 新增,修改,刪除表的列,約束等表的定義。檢視列 desc 表名 修改表名 alter table t book rename to bbb 新增列 alter table 表名 add column 列名 varchar 30 刪除列 alter table 表名 drop ...