2012-01-12 53 views
0

我正在一個項目,我需要從數據庫中獲取最小和最大日期,以及字段的第一部分substringing字符和該字段分組。所以在數據庫基本上我有MySQL的最小和最大日期與分組和子字符串

2012-01-01 Unknown username/password attempted to login. User: admin

2012-01-01 Failed to add user account. MySQL Error: certain my sql error Unknown

2012-01-02 Failed to add user account. MySQL Error: certain my sql error Unknown

2012-01-04 Unknown username/password attempted to login. User: administrator

下面是我使用的是工作查詢,而不顯示日期

SELECT ala_type, partMsg, 
wholeMsg, ala_level, ala_page, COUNT(wholeMsg) AS msgCount FROM 
(
SELECT ala_type, SUBSTRING_INDEX(ala_message, ':', 1) AS partMsg, ala_message AS wholeMsg, 
ala_level, ala_page FROM alarms a) p 
GROUP BY partMsg 

此位是正確的分組如預期,但如果我嘗試添加min(date_field),它只顯示一條記錄。

下面是我試圖

SELECT ala_date, min(ala_date), max(ala_date), ala_type, partMsg, wholeMsg, ala_level, ala_page, COUNT(wholeMsg) AS msgCount FROM ( SELECT ala_date, min(ala_date), max(ala_date), ala_type, SUBSTRING_INDEX(ala_message, ':', 1) AS partMsg, ala_message AS wholeMsg, ala_level, ala_page FROM alarms a) p GROUP BY partMsg

如果我不把ala_date在第二份聲明,只是有分鐘(ala_date)查詢它說,它無法找到現場ala_date。然而,當我運行查詢,我只得到一個記錄,我沒有料想到會看到下面的

2012-01-01 2012-01-04 Unknown username/password attempted to login.User: 2

2012-01-01 2012-01-02 Failed to add user account. MySQL Error: > certain mysql error 2

的2和預期的結果到底是多少次發生的消息計數。

什麼其實我得到的是:

2012-01-01 2012-01-01 2012-01-01 Failed to add user account... 1

現在只顯示1個記錄和最小值和最大值僅是相同的,計數爲1而不是2

我該怎麼辦做得到我期待得到的。

感謝您提供的任何幫助。

回答

0

你會做一些像(我的mysql是生鏽的),但theoiry是健全的。

Select SomeDate,SomeMessage From SomeTable 
inner join (
Select Min(SomeDate) as SomeDate From SomeTable) earliest 
On earliestDate.SomeDate = SomeTable.SomeDate 

即找到每個組的最短日期,然後再回到原始表來查找同一日期的記錄。