2016-03-09 105 views
0

的最大日我想從每個WishContent基礎上,wishContent.wishId最新的日期,這樣,如果我有wishContents這樣的:SQL查詢來獲取

ID DATE 
#1 : 09-03-2016 
#1 : 08-03-2016 
#1 : 03-04-2016 
#2 : 09-02-2016 
#2 : 04-01-2016 

然後我只想:

#1 09-03-2016 
#2 09-02-2016 

SELECT 
     wish.Status, 
     wish.Id, 
     wish.User, 
     wish.CompletionDate, 
     wishContent.Content, 
     wishContent.Title, 
     wishContent.Country, 
     wishContent.City, 
     wishContent.IsAccepted, 
     wishContent.moderator_Username, 
     MAX(wishContent.Date) AS max_date 
     FROM `wish` JOIN wishContent on wish.Id = wishContent.wish_Id 
     GROUP BY wish.Id where wish.Date 
     ORDER BY max_date DESC 

任何人都可以幫助我嗎?

+0

http://dev.mysql.com/doc/refman/5.7/en/example-maximum-column-group-row .html – CBroe

+0

WHERE通常在GROUP BY之前。 –

回答

3

我想你需要一個額外的連接來獲得所需的結果:

SELECT 
     w.Status, 
     w.Id, 
     w.User, 
     w.CompletionDate, 
     wc.Content, 
     wc.Title, 
     wc.Country, 
     wc.City, 
     wc.IsAccepted, 
     wc.moderator_Username, 
     wcMax.max_date 
     FROM wish AS w 
     JOIN (SELECT wish_Id, MAX(wishContent.Date) AS max_date 
      FROM wishContent 
      GROUP BY wish_Id 
    ) AS wcMax ON w.Id = wcMax.wish_Id 
     JOIN wishContent AS wc on wcMax.wish_Id = wc.wish_Id AND wc.Date = wcMax.max_date 
     WHERE wish.Date 
     ORDER BY max_date DESC 
+0

發生以下錯誤:#1064 - 您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'FROM wishContent GROUP BY wish_Id '附近使用正確的語法。「第15行的wcMAx ON w.Id = wcMax' –

+0

@M1Ö對不起,查詢中存在拼寫錯誤:我刪除了'',''在'max_date'之後。你可以再試一次嗎? –

+0

它的作品!你是英雄,非常感謝你! –

1

嘗試這個

SELECT * FROM (
SELECT 
     wish.Status, 
     wish.Id, 
     wish.User, 
     wish.CompletionDate, 
     wishContent.Content, 
     wishContent.Title, 
     wishContent.Country, 
     wishContent.City, 
     wishContent.IsAccepted, 
     wishContent.moderator_Username, 
     MAX(STR_TO_DATE(wishContent.Date,'%d-%m-%Y')) AS max_date 
     FROM `wish` JOIN wishContent on wish.Id = wishContent.wish_Id 
     GROUP BY wish.Id 
    ) AS t 
     ORDER BY t.max_date DESC; 

我假設你的日期格式爲DD-MM-YYYY。

+0

不幸的是不起作用 –

+0

什麼是錯誤? –

+0

不是一個錯誤,我沒有得到最新的。 –