1. 程式人生 > >Sql中日期型別的比較

Sql中日期型別的比較

一.儲存日期的欄位為日期型別

MySql(Date、DateTime、TimeStamp等):
方法一:直接比較
select * from test where create_time between ‘2015-03-03 17:39:05’ and ‘2016-03-03 17:39:52’;

方法二:用unix_timestamp函式,將字元型的時間,轉成unix時間戳
select * from test where unix_timestamp(create_time) > unix_timestamp(‘2011-03-03 17:39:05’) and unix_timestamp(create_time) < unix_timestamp(‘2011-03-03 17:39:52’);
個人覺得這樣比較更踏實點兒。

Oracle(Date,TimeStamp等):
方法一:將字串轉換為日期型別
select * from test where create_time between to_date(‘2015-03-03 17:39:05’) and to_date(‘2016-03-03 17:39:52’);

二.儲存日期型別的欄位為數值型別

MySql(bigint):
方法一:將日期字串轉換為時間戳
select * from test where create_time > unix_timestamp(‘2011-03-03 17:39:05’) and create_time< unix_timestamp(‘2011-03-03 17:39:52’);

方法二:將時間戳轉換為日期型別
select * from test where from_unixtime(create_time/1000) between ‘2014-03-03 17:39:05’ and ‘2015-03-03 17:39:52’);