MySQL建立表注意事項和操作表結構
建立表注意事項
- 表中多個欄位用逗號隔開,最後一個欄位的結尾不要存在逗號
- 資料表名不要和欄位重名
- auto_increment 屬性 依賴於主鍵
- 表名稱和欄位名避免和關鍵字衝突
操作表結構
-
給表新增新的欄位
alter table 表名 add 欄位名 欄位型別[ 約束條件] [ 說明 ]
alter table test9 add username varchar(10) not null default 'xxxx' comment '使用者名稱';
-
刪除欄位
alter table 表名 drop 欄位名;
alter table test9 drop a;
-
更改欄位名稱
alter table 表名 change 原欄位名 新欄位名 欄位型別[ 約束條件] [ 說明 ]
alter table test9 change a age tinyint default 18;
-
修改欄位資訊
alter table 表名 modify 欄位名 欄位型別[ 約束條件] [ 說明 ]
alter table test9 modify age int default 18;
-
更改欄位位置
first 排在第一位
after 在哪個欄位後面
-
放在首位
alter table 表名 modify 欄位名 欄位型別[ 約束條件] [ 說明 ] first
alter table test9 modify age tinyint default 18 first;
-
在哪個欄位後面
alter table 表名 modify 欄位名 欄位型別[ 約束條件] [ 說明 ] after 欄位名
alter table test9 modify username varchar(10) default 'xxx' after age;
-
-
新增索引
-
新增索引名
alter table 表名 add 索引型別 索引名稱(欄位名)
alter table test9 add key k_username(username);
alter table test9 add unique u_age(age);
-
不新增索引名
alter table 表名 add 索引型別(欄位名)
alter table test9 add key(username);
alter table test9 add unique(age);
-
-
刪除索引
alter table drop key 索引名稱;
alter table test9 drop key u_age;
-
修改表和欄位字元編碼(瞭解)
alter table 表名 character set 字元編碼;
alter table 表名 modify 欄位名 欄位型別[ 約束條件] [ 說明 ] character set utf8;