MySQLの文字列からtimestampへのキャストについて
たとえば”2009-02-01″という文字列はtimestamp型にキャストされる際に、”2009-02-01 00:00:00″として扱われます。
なので、以下のようなデータベースがあった場合。
mysql> select * from hoge; +----+---------------------+ | id | created_at | +----+---------------------+ | 1 | 2009-02-01 00:00:00 | | 2 | 2009-02-01 00:00:01 | +----+---------------------+ 2 rows in set (0.00 sec)
2月1日を取得したい場合、以下は間違い。
mysql> select * from hoge where created_at = '2009-02-01'; +----+---------------------+ | id | created_at | +----+---------------------+ | 1 | 2009-02-01 00:00:00 | +----+---------------------+ 1 row in set (0.00 sec)
date型でキャストして比較するか、今日以降次の日より前の条件にする。
mysql> select * from hoge where date(created_at) = '2009-02-01'; +----+---------------------+ | id | created_at | +----+---------------------+ | 1 | 2009-02-01 00:00:00 | | 2 | 2009-02-01 00:00:01 | +----+---------------------+ 2 row in set (0.00 sec)
mysql> select id, created_at from chat where created_at >= '2009-02-01' and created_at < '2009-02-02'; +----+---------------------+ | id | created_at | +----+---------------------+ | 1 | 2009-02-01 00:00:00 | | 2 | 2009-02-01 00:00:01 | +----+---------------------+ 2 rows in set (0.00 sec)
カテゴリー: 日記