先看一下最簡單的例子,在test中,添加一個字段,字段名為birth,類型為date類型。
mysql> alter table test add column birth date;
Query OK, 0 rows affected (0.36 sec)
Records: 0 Duplicates: 0 Warnings: 0
查詢一下數據,看看結果:
mysql> select * from test;
+------+--------+----------------------------------+------------+-------+
| t_id | t_name | t_password | t_birth | birth |
+------+--------+----------------------------------+------------+-------+
| 1 | name1 | 12345678901234567890123456789012 | NULL | NULL |
| 2 | name2 | 12345678901234567890123456789012 | 2013-01-01 | NULL |
+------+--------+----------------------------------+------------+-------+
2 rows in set (0.00 sec)
從上面結果可以看出,插入的birth字段,默認值為空。我們再來試一下,添加一個birth1字段,設置它不允許為空。
mysql> alter table test add column birth1 date not null;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
居然執行成功了?。恳馔饬?!我原來以為,這個語句不會成功的,因為我沒有給他指定一個默認值。我們來看看數據:
mysql> select * from test;
+------+--------+----------------------------------+------------+-------+------------+
| t_id | t_name | t_password | t_birth | birth | birth1 |
+------+--------+----------------------------------+------------+-------+------------+
| 1 | name1 | 12345678901234567890123456789012 | NULL | NULL | 0000-00-00 |
| 2 | name2 | 12345678901234567890123456789012 | 2013-01-01 | NULL | 0000-00-00 |
+------+--------+----------------------------------+------------+-------+------------+
2 rows in set (0.00 sec)
哦,明白了,系統自動將date類型的值,設置了一個默認值:0000-00-00。下面我來直接指定一個默認值看看:
mysql> alter table test add column birth2 date default '2013-1-1';
Query OK, 0 rows affected (0.28 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select * from test;
+------+--------+----------------------------------+------------+-------+------------+------------+
| t_id | t_name | t_password | t_birth | birth | birth1 | birth2 |
新聞熱點
疑難解答