2014-10-08 226 views
0

我一直在尋找一段時間,並沒有找到一個有效的例子。希望你能發現明顯的錯誤!MySQL ORDER BY,GROUP BY內JOIN

SELECT 
     Timestamp 
     , i_currency.Code AS Code 
     , Conversion 
    FROM 
     i_convert(
      SELECT 
       Timestamp 
       , Conversion 
      FROM 
       i_convert 
      ORDER BY Timestamp DESC 
     ) 
     JOIN i_currency 
      ON i_convert.CurrencyID = i_currency.CurrencyID 
    GROUP BY Code 

我不確定JOIN應該在哪裏,它應該在括號裏,還是在外面或兩者都有?我已經嘗試了所有三個沒有運氣,不斷得到:

You have an error... ...near '(SELECT Timestamp , Conversion FROM i_convert ORDER ' 
+0

@Strawberry:我認爲這應該是別名。 – 2014-10-08 17:14:28

+0

@Strawberry沒有這樣的功能。他希望將其用作SELECT結果的別名。看這裏:'ON i_convert.CurrencyID = i_currency.CurrencyID' – user4035 2014-10-08 17:14:36

+2

我認爲這是漿果味諷刺。 :) – paqogomez 2014-10-08 17:14:59

回答

1

最初的查詢沒有意義。它使用GROUP BY,但試圖選擇既不分組列也不聚合函數的列。對於任何給定的結果行,預計哪種時間戳和哪種轉換?

我想目標是選擇每種貨幣的最新轉換。這可能看起來更像這樣:

SELECT 
    latest.Timestamp AS Timestamp 
    , i_currency.Code AS Code 
    , i_convert.Conversion AS Conversion 
FROM i_currency 
    JOIN i_convert 
     ON i_convert.CurrencyID = i_currency.CurrencyID 
    JOIN (
     SELECT MAX(Timestamp) as Timestamp, CurrencyId 
     FROM i_convert 
     GROUP BY CurrencyId 
    ) latest 
     ON i_convert.Timestamp = latest.Timestamp 
      AND i_convert.CurrencyId = latest.CurrencyId 
+0

賓果,你釘了它。非常感謝! – iforwms 2014-10-09 01:40:23

+0

那麼也許你會在意接受答案? – 2014-10-09 15:13:51