2010-03-17 651 views
2

是否有任何方法使用mysql DATE列獲取自日期以來的月數和年數?Mysql - 獲取月份和年份#

所以,如果我輸入1/1/2009 ..我想1年,3個月..等等。

+0

那麼,這是2010年,這將是1年。目前3月17日,超過3個月。所以jwzk是對的。 – 2010-03-17 15:20:08

回答

3

DateDiff可以返回兩個日期之間的天數的差異。 從那裏,你可能必須自己做數學。您可以使用所有邏輯創建存儲過程,但大多數情況下,SQL不是作爲功能語言設計的。

編輯:我找到了你要找的東西。試試這個:

DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), <date>)), '%c months and %Y years') 
+0

從datediff()結果中提取幾個月是很困難的,因爲幾個月的月份會有所不同。如果你忽略了閏年,年份將會接近。 – 2010-03-17 15:08:43

0
select mnth as months_between, mnth/12 as years_between 
from 
(select (year(<current date column>) - year(<older date column>))*12 + 
     (month(<current date column>) - month(<older date column)) as mnth 
    from <tables with date columns> 
    where <conditions to get your rows with the dates you need to compare> 
) 

而且比照Anthony Mollinaro的SQL Cookbook,關於Date Arithmetic的第8章。

+1

如果您想使用今天的日期,可以用NOW()替換當前日期列。 – 2010-03-17 15:08:52

+0

並非100%準確,因爲您可能會遇到類似2009/03/15 2009/02/16的情況。這不會是1個月,但腳本的返回值是。 – 2010-03-17 15:19:00

+0

我認爲這取決於OP的業務需求,兩者之間的比較是否爲1/0。但是,是的,你在技術上是正確的。 – 2010-03-17 15:34:12