MySQL5.6で作成日時と更新日時を自動で設定してみる

MySQL5.6で作成日時と更新日時を自動で設定してみる。


MySQLのバージョンは「5.6.23」。

select version();
+-----------+
| version() |
+-----------+
| 5.6.23    |
+-----------+

作成日時に「current_timestamp」
更新日時に「current_timestamp on update current_timestamp」
を設定したテーブルを作成する。

create table sample (
  id         int,
  val        varchar(16),
  created_at timestamp not null default current_timestamp,
  updated_at timestamp not null default current_timestamp on update current_timestamp,
  primary key(id)
);

下記のようなテーブルが作成される。

desc sample;
+------------+-------------+------+-----+-------------------+-----------------------------+
| Field      | Type        | Null | Key | Default           | Extra                       |
+------------+-------------+------+-----+-------------------+-----------------------------+
| id         | int(11)     | NO   | PRI | 0                 |                             |
| val        | varchar(16) | YES  |     | NULL              |                             |
| created_at | timestamp   | NO   |     | CURRENT_TIMESTAMP |                             |
| updated_at | timestamp   | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------+-------------+------+-----+-------------------+-----------------------------+

レコードを追加する。

insert into sample (id, val) values (1, 'aaa');

作成日時と更新日時が自動で設定されているのが確認できる。

select * from sample;
+----+------+---------------------+---------------------+
| id | val  | created_at          | updated_at          |
+----+------+---------------------+---------------------+
|  1 | aaa  | 2015-03-12 17:30:36 | 2015-03-12 17:30:36 |
+----+------+---------------------+---------------------+

更新すると、

update sample set val = 'bbb' where id = 1;

更新日時だけが変わる。

select * from sample;
+----+------+---------------------+---------------------+
| id | val  | created_at          | updated_at          |
+----+------+---------------------+---------------------+
|  1 | bbb  | 2015-03-12 17:30:36 | 2015-03-12 17:31:07 |
+----+------+---------------------+---------------------+

ただし、UPDATEしても値が変わっていない場合は、更新日時も変わらない。

update sample set val = 'bbb' where id = 1;
select * from sample;
+----+------+---------------------+---------------------+
| id | val  | created_at          | updated_at          |
+----+------+---------------------+---------------------+
|  1 | bbb  | 2015-03-12 17:30:36 | 2015-03-12 17:31:07 |
+----+------+---------------------+---------------------+

ちなみに、MySQLのバージョンが古いと、テーブル作成時にエラーがでる。

create table sample (
  id         int,
  val        varchar(16),
  created_at timestamp not null default current_timestamp,
  updated_at timestamp not null default current_timestamp on update current_timestamp,
  primary key(id)
);
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause