話說有一文章表article,存儲文章的添加文章的時間是add_time字段,該字段為int(5)類型的,現需要查詢今天添加的文章總數並且按照時間從大到小排序,則查詢語句如下:
SELECT * FROM `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d');或:
SELECT * FROM `article` where to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = to_days(now());假設以上表格的add_time欄位的儲存類型是DATETIME類型或TIMESTAMP類型,則查詢語句也可如下寫法:
SELECT * FROM `article` where to_days(`add_time`) = to_days(now());
SELECT * FROM `article` where to_days(now()) – to_days(`add_time`) <= 1;🟎reee 7天的資訊記錄:
SELECT * FROM `article` where date_sub(curdate(), INTERVAL 7 DAY) <= date(`add_time`);
SELECT * FROM `article` where date_sub(curdate(), INTERVAL 30 DAY) <= date(`add_time`);
SELECT * FROM `article` where date_format(`add_time`, ‘%Y%m') = date_format(curdate() , ‘%Y%m');
SELECT * FROM `article` where period_diff(date_format(now() , ‘%Y%m') , date_format(`add_time`, ‘%Y%m')) =1;對上面的SQL語句中的幾個一月函數做一下分析:
mysql> select to_days('2010-11-22 14:39:51'); +--------------------------------+ | to_days('2010-11-22 14:39:51') | +--------------------------------+ | 734463 | +--------------------------------+ mysql> select to_days('2010-11-23 14:39:51'); +--------------------------------+ | to_days('2010-11-23 14:39:51') | +--------------------------------+ | 734464 | +--------------------------------+可以看出22日與23日的差別就是,轉換之後的數增加了1,這個粒度的查詢是比較粗糙的,有時可能不能滿足我們的查詢要求,那麼就需要使用細粒度的查詢方法str_to_date函數了,下面將分析這個函數的用法。
mysql> select to_days('1997-10-07'), to_days('97-10-07'); -> 729669, 729669(2)str_to_date
mysql> select str_to_date("2010-11-23 14:39:51",'%Y-%m-%d %H:%i:%s'); +--------------------------------------------------------+ | str_to_date("2010-11-23 14:39:51",'%Y-%m-%d %H:%i:%s') | +--------------------------------------------------------+ | 2010-11-23 14:39:51 | +--------------------------------------------------------+具體案例操作如下:
select str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s') from article where str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s')>='2012-06-28 08:00:00' and str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s')<='2012-06-28 09:59:59';