Mysql修改約束,列資訊,表資訊

2021-07-26 14:11:17 字數 2773 閱讀 5352

修改資料表:

新增單列:

alter

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

column];

(預設在末尾)

例如在usename後面新增列:

alter

table users1 add password varchar(20) not

null

after username

在所有列的最前面新增列

alter table users1 add password varchar(20) not null first;

新增多列:alter table tbl_name add [column] (col_name col_definition,...);(無法指定位置,只能在末尾)
刪除單列:alter table tbl_name drop [column] col_name;

例如:

alter

table users1 drop truename;

刪除多列:alter table tbl_name drop [column] col_name,drop [column] col_name,...;
建立乙個測試的表

create

table users2(

usename varchar(20) not

null,

pid smallint unsigned);

增加列alter

table users2 add id smallint unsigned;

新增主鍵約束

標準:

**alter

table tbl_name add [constraint [symbol]] primary

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

symbol為primary key的別名。**

例子:alter

table users2 add

constraint pk_users2_id primary

key(id);

新增唯一約束

alter

table users2 add

unique(username);

新增外來鍵約束

alter

table users2 add

foreign

key(pid) references provinces(id);

新增/刪除預設約束

alter

table users2 add age tinyint unsigned not

null;//新增一列

新增預設約束

alter

table users2 alter age set

default

15;刪除預設約束

alter

table users2 alter age drop

default;

刪除主鍵約束

alter

table users2 drop

primary

key;

刪除唯一約束

alter

table users2 drop index username;//刪除的是約束,而不是字段

刪除外來鍵約束

先查詢外鍵名字

show

create

table users2;

alter

table users2 drop

foreign

key users2_ibfk_1;

修改位置

alter

table users2 modify id smallint unsigned not

null

first;

修改型別

alter

table users2 modify id tinyint unsigned not

null;

修改列的名稱,從pid 改為 p_id

alter

table users2 change pid p_id tinyint unsigned not

null;

修改資料表的名字

alter

table users2 rename users4;

MySQL修改約束

alter table 表名 modify column 欄位名 字段型別 新約束 例如 alter table student modify column age int not null 新增字段唯一 alter table student modify column stu nu varcha...

MySQL修改約束

新增主鍵約束 alter table tbl name add constraint symbol索引名 primary key index type index col name1,index col name2,刪除主鍵約束 alter table tbl name drop primary k...

Mysql修改表備註, 列資訊

1 新增表和字段的注釋 建立資料表的同時,給表和字段新增注釋 建立使用者資訊表 create table tb user id int auto increment primary key comment 編號 name varchar 30 comment 姓名 comment 使用者資訊表 2 ...