2015-07-28 26 views
1

我有一個表myTable如何在MySQL中使用變量進行SELECT?

Id  userID month year login day 
    1628325 812467 1  2015 1 6 
    1628326 969054 1  2015 2 9 
    1628327 812467 2  2015 1 27 
    1628328 811602 2  2015 1 27 
    1628329 952056 3  2015 3 2 
    1628330 1082029 3  2015 5 2 
    1628337 952056 3  2015 1 3 
    1628338 952056 3  2015 6 4 
    1628339 812467 3  2015 2 4 
    1628340 1082029 3  2015 2 4 
    1628341 811602 3  2015 4 4 
    1628349 1081988 3  2015 1 4 

我需要時間來算登錄的總數。 我有2個傳入變量:startDate和:endDate。所以選擇應該是這樣的:

SELECT DATE_FORMAT(Date, '%Y/%m/%d') "Day", sum(login) FROM myTable WHERE Date >=:startDate AND Date<:endDate ORDER BY Date DESC

如何實現的呢?

的變量來自於JSP page

從調試模式在Eclipse中我可以看到:的startDate和:那來自jsp頁面結束日期變量 - 具有以下格式:

週三7月1 00:00:00 EEST 2015年,星期二07月28日00:00:00 EEST 2015年

當我運行它沒有顯示任何報告。可能是時間格式表示的問題? (%y-%m-%d)或(%y /%m /%d)或..

+0

其中ara變量來自哪裏? –

+0

你必須使用羣組 – Raghavendra

+0

閱讀有關java中準備的語句 – Jens

回答

1

您可以從組件構建日期。一種方法是使用str_to_date()。但是,您確實應該將日期存儲爲日期,而不是單個組件。 MySQL對日期有很好的支持,所以你應該使用數據庫的這些功能。

這裏有一種方法:

SELECT str_to_date(concat_ws('-', year, month, day), '%Y-%m-%d') as date, sum(login) 
FROM myTable 
WHERE str_to_date(concat_ws('-', year, month, day), '%Y-%m-%d') >= :startDate AND 
     str_to_date(concat_ws('-', year, month, day), '%Y-%m-%d') < :endDate 
GROUP BY date 
ORDER BY date; 

的替代方案,需要更多的處理,但更容易編寫是使用having

SELECT str_to_date(concat_ws('-', year, month, day), '%Y-%m-%d') as date, sum(login) 
FROM myTable 
GROUP BY date 
HAVING date >= :startDate and date < :endDate 
ORDER BY date; 

這是效率較低,因爲它經過對數據進行過濾聚合整個表的

+0

非常感謝您的回答! – Dan

相關問題