MySQL中的ORDER BY,GROUP BY

时间:2014-10-08 17:12:06

标签: mysql sql 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 '

1 个答案:

答案 0 :(得分: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