반응형

출처: http://mysqlblog.fivefarmers.com/2012/05/29/overlooked-mysql-5-6-new-features-timestamp-and-datetime-improvements/


MySQL 5.6 은 현재 개발중에 있습니다. 버전이 올라가면 기능이 향상되는데, TIMESTAMP 와 DATETIME 의 데이터 타입(Data Type)을 사용하는 컬럼에 경우 Update, Insert 시에 몇가지 기능이 향상되었습니다.


mysql> CREATE TABLE test_date (
    -> a INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> b INT,
    -> created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    -> updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    -> );
Query OK, 0 rows affected (0.03 sec)


여기서 주목해야 할 것은 'created TIMESTAMP DEFAULT CURRENT_TIMESTAMP'와 'updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' 입니다.


mysql> desc test_date;
+---------+------------------+------+-----+---------------------+-----------------------------+
| Field   | Type             | Null | Key | Default             | Extra                       |
+---------+------------------+------+-----+---------------------+-----------------------------+
| a       | int(10) unsigned | NO   | PRI | NULL                | auto_increment              |
| b       | int(11)          | YES  |     | NULL                |                             |
| created | timestamp        | NO   |     | CURRENT_TIMESTAMP   |                             |
| updated | timestamp        | NO   |     | 0000-00-00 00:00:00 | on update CURRENT_TIMESTAMP |
+---------+------------------+------+-----+---------------------+-----------------------------+
4 rows in set (0.03 sec)

Default와 Extra 컬럼에 내용을 자세히 보십시오.


여기서 Insert 를 다음과 같이 합니다.


mysql> INSERT INTO test_date SET b=1;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM test_date;
+---+------+---------------------+---------------------+
| a | b    | created             | updated             |
+---+------+---------------------+---------------------+
| 1 |    1 | 2012-06-12 17:07:20 | 0000-00-00 00:00:00 |
+---+------+---------------------+---------------------+
1 row in set (0.00 sec)


'created' 컬럼에 자동으로 시간이 등록됩니다. 과거에는 다음과 같이 해줬어야 했습니다.


mysql> INSERT INTO test_date SET b=1, created=now();


'now()' 함수를 사용해서 했어야 했지만 mysql 5.6 에서 TIMESTAMP 타입을 이용해서 컬럼을 정의하면 더 손쉽게 자동으로 처리를 해줍니다.


다음과 같이 Update 를 해봅니다.


mysql> UPDATE test_date SET b = b+1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM test_date;
+---+------+---------------------+---------------------+
| a | b    | created             | updated             |
+---+------+---------------------+---------------------+
| 1 |    2 | 2012-06-12 17:07:20 | 2012-06-12 17:11:48 |
+---+------+---------------------+---------------------+
1 row in set (0.00 sec)


update 필드에 값이 자동으로 시간이 업데이트 됩니다. DATETIME 도 이와 같은데 다른점은 값이 없을 경우 'NULL'이 됩니다. 


mysql> CREATE TABLE test_date2 (
    -> a INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> b INT,
    -> created DATETIME DEFAULT CURRENT_TIMESTAMP,
    -> updated DATETIME ON UPDATE CURRENT_TIMESTAMP
    -> );
Query OK, 0 rows affected (0.00 sec)


반응형

+ Recent posts