某位同事要求对某张表(innodb表,且已有数据)增添一个字段,无默认值要求:
添加之前的表中数据:
01 mysql> select * from t1; 02 +------+ 03 | id | 04 +------+ 05 | 1 | 06 | 2 | 07 | 3 | 08 +------+ 09 3 rows in set (0.02 sec) 10 11 mysql> alter table t1 add col1 char(1); 12 query ok, 3 rows affected (0.24 sec) 13 records: 3 duplicates: 0 warnings: 0 添加字段之后的表中数据:
1 mysql> select * from t1; 2 +------+------+ 3 | id | col1 | 4 +------+------+ 5 | 1 | null | 6 | 2 | null | 7 | 3 | null | 8 +------+------+ 9 3 rows in set (0.00 sec) 过了一会儿,他要求设置新添字段的默认值为'n':
1 mysql> alter table t1 modify col1 char(1) default 'n'; 2 query ok, 0 rows affected (0.05 sec) 3 records: 0 duplicates: 0 warnings: 0 查看此时的表中数据:
1 mysql> select * from t1; 2 +------+------+ 3 | id | col1 | 4 +------+------+ 5 | 1 | null | 6 | 2 | null | 7 | 3 | null | 8 +------+------+ 9 3 rows in set (0.00 sec) 操作到这里,可以说同事的这个需求就算告一段落了。不过如果把刚才的时间倒回到这个小需求的开始点,同事如果一次性的提出了完整的需求:添加一个char(1)类型的字段,默认值为‘n’:
01 mysql> alter table t1 add col1 char(1) default 'n'; 02 query ok, 3 rows affected (0.19 sec) 03 records: 3 duplicates: 0 warnings: 0 04 查看表中数据: 05 mysql> select * from t1; 06 +------+------+ 07 | id | col1 | 08 +------+------+ 09 | 1 | n | 10 | 2 | n | 11 | 3 | n | 12 +------+------+ 13 3 rows in set (0.00 sec) 两次基本上相同的操作,但表中旧数据中的新添字段的结果却是不一样的。
我记录这段操作过程并不是想说明字段类型填充的默认值的原理,因为它不是一个复杂的概念,只是觉得日后需留意一些类似的小细节。
bitscn.com
