1. 往已經建好資料的表中插入一個字段
參考文檔= http://c.biancheng.net/view/7201.html
-- 基本格式
ALTER TABLE <表名> ADD <新字段名><資料類型>[限制條件];
-- 示例, 普通在表的最後面加上一個字段
alter table student add status_cd int(2) comment '使用狀态';
--說明:alter table + 表名 + add + 要添加的字段 + 字段類型 + comment "0盈利,1虧損" + after + 要跟随的字段名 ; (在這個字段後面添加一個字段)
-- 在表的首列加入一個字段
alter table student add s_id bigint(25) comment '使用者編号' first;
-- 在指定字段後面加如一個字段
alter table student add age int(25) comment '使用者年齡' after name;
2. 工作中遇見的問題(添加一個自增的主鍵id)
參考文檔 = http://c.biancheng.net/view/7624.html
以上是日常的操作, 今天遇見一個問題, 需要為已經建立好的表添加一個自增的主鍵id
-- 在首列
alter table student add id int(25) PRIMARY KEY AUTO_INCREMENT comment '使用者id' first;
需要将這個自增的id設為主鍵, 不然會報錯, 以下内容會報錯
-- 在首列
alter table student add id int(25) AUTO_INCREMENT comment '使用者id' first;
3. 為一個沒有預設值的,設定一個預設值
參考文檔 = https://blog.csdn.net/expect521/article/details/80945928
直接插入這個字段, 但是沒有設定預設值
-- 在指定字段後面加如一個字段
alter table student add sex int(2) comment '使用者性别0 男,1 女' after age;
重新寫一個腳本, 為上面的字段添加一個預設值
注意觀察兩者的差別點
-- 在指定字段後面加如一個字段
alter table student alter sex DEFAULT 0;
或者,在新增這個字段的時候就為他設定一個預設值
-- 在指定字段後面加如一個字段
alter table student add sex int(2) DEFAULT 0 comment '使用者性别0 男,1 女' after age;