2014-01-06 65 views
0

選擇數據我有這樣的代碼從我的數據庫中的數據,從本月中進行選擇:從上個月SQL

SELECT * FROM daily_reports 
WHERE username = '$username' and MONTH(date) = MONTH(Now()) 
order by date DESC 

,現在我想從上個月顯示數據。

列日期型日期

+1

注:這會給你從當月的數據在每年 –

+2

'MONTH(DATE_SUB(NOW(),間隔1 MONTH))' –

+1

我明確地認爲這可以幫助你。 http://stackoverflow.com/questions/1479745/mysql-last-month-date-statement – gpopoteur

回答

1

這應該工作: -

SELECT * 
FROM daily_reports 
WHERE username = '$username' 
and MONTH(date) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH)) 
order by date DESC 
+0

它的工作原理!謝謝。到上週和本週如何展示? – user3164987

+0

在您的聲明中使用BETWEEN。 –

+0

這也將爲您提供數據可用的每一年的指定月份的數據。 –

0
SELECT 
    * 
FROM 
    daily_reports 
WHERE username = '$username' 
    AND dateColumn BETWEEN SUBDATE(CURDATE(), INTERVAL 1 MONTH) AND NOW(); 
ORDER BY DATE DESC 
2

試試這個

SELECT * FROM daily_reports 
WHERE username = '$username' 
and MONTH(date) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH)) order by date DESC 
0

您可以在日期完成許多操作,如圖所示罰款手冊。

在你的情況,也許DATE_SUB function將是清楚的:

SELECT * FROM daily_reports 
WHERE username = '$username' AND MONTH(date) = MONTH(DATE_SUB(Now(), INTERVAL 1 MONTH) 
ORDER BY date DESC 
0
date BETWEEN date_format 
(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') 
AND last_day(NOW() - INTERVAL 1 MONTH)