1

我正在尝试做一个简单的 mysql 请求,但我遇到了问题。

我有 2 个表定义如下:

currencies
______________________________________________________________________________________
currency_id | currency_name | currency_symbol | currency_active | currency_auto_update

exchange_rates
____________________________________________________________________________________________________
exchange_rate_id | currency_id | exchange_rate_date | exchange_rate_value | exchange_rate_added_date

我想要做的是exchange_rates为活动货币选择里面的最后一行。

我是这样做的:

SELECT c.currency_id, c.currency_name, c.currency_symbol, c.currency_active, er.exchange_rate_id, er.exchange_rate_date, er.exchange_rate_value
FROM currencies c
LEFT JOIN (
    SELECT er1.exchange_rate_id, er1.currency_id, er1.exchange_rate_date, er1.exchange_rate_value
    FROM exchange_rates er1
    ORDER BY er1.exchange_rate_date DESC
    LIMIT 1
    ) AS er
ON er.currency_id=c.currency_id
WHERE c.currency_active='1'

即使有匹配的行,这也会NULL从表中返回值exchange_rates

我试图删除LIMIT 1,但如果我这样做,我会返回所有活动货币的行,这不是我想要的解决方案

这个查询应该是什么样子?

谢谢!

4

2 回答 2

3

试试这个:

SELECT c.currency_id, c.currency_name, c.currency_symbol, c.currency_active, er.exchange_rate_id, er.exchange_rate_date, er.exchange_rate_value
FROM currencies c
LEFT JOIN (SELECT * FROM 
    (SELECT er1.exchange_rate_id, er1.currency_id, er1.exchange_rate_date, er1.exchange_rate_value
    FROM exchange_rates er1
    ORDER BY er1.exchange_rate_date DESC) AS A GROUP BY currency_id 
    ) AS er
ON er.currency_id=c.currency_id
WHERE c.currency_active='1' 
于 2012-11-19T11:46:28.903 回答
0

查询的想法对我来说是正确的。您的左连接查询应返回具有最新汇率的行。你可以在这里使用内部连接,因为必须有一种货币引用这个......

SELECT c.currency_id, c.currency_name, c.currency_symbol, c.currency_active, er.exchange_rate_id, er.exchange_rate_date, er.exchange_rate_value
FROM currencies c
INNER JOIN exchange_rates_er1 e ON e.currency_id = c.currency_id
WHERE c.currency_active='1'
ORDER BY e.exchange_rate_date DESC
LIMIT 1
于 2012-11-19T11:39:57.307 回答