我正在尝试做一个简单的mysql请求而且我遇到了问题。
我有两个表定义如下:
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
,但如果我这样做,则返回活动货币的所有行,这不是我想要的解决方案
这个查询应该如何?
谢谢!
答案 0 :(得分: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'
答案 1 :(得分: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