【发布时间】:2012-07-23 14:50:49
【问题描述】:
下表将存储不同货币之间的汇率随时间变化:
CREATE TABLE `currency_exchange` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`currency_from` int(11) DEFAULT NULL,
`currency_to` int(11) DEFAULT NULL,
`rate_in` decimal(12,4) DEFAULT NULL,
`rate_out` decimal(12,4) DEFAULT NULL,
`exchange_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
如何查询它以获取最新汇率列表?
它本质上是将组合的 currency_from 和 currency_to 列识别为不同的汇率,然后找到日期最近的那个。
例如,假设我的数据如下:
INSERT INTO currency_exchange (id, currency_from, currency_to, rate_in, rate_out, exchange_date) VALUES
(1, 1, 2, 0.234, 1.789, '2012-07-23 09:24:34'),
(2, 2, 1, 0.234, 1.789, '2012-07-24 09:24:34'),
(3, 2, 1, 0.234, 1.789, '2012-07-24 09:24:35'),
(4, 1, 3, 0.234, 1.789, '2012-07-24 09:24:34');
我希望它选择行 ID:
- 1 - 作为货币 1 和 2 之间的最新汇率
- 3 - 作为货币 2 和 1 之间的最新汇率
- 4 - 作为货币 1 和 3 之间的最新汇率
【问题讨论】:
-
很遗憾您没有使用 PostgreSQL...在那里您可以使用
SELECT DISTINCT ON (currency_from, currency_to) * FROM currency_exchange ORDER BY currency_from, currency_to, exchange_date DESC。 MySQL 缺少表达此功能的语法。 -
@cdhowie 另外,有时人们只想坚持使用标准 SQL,因此 PostgreSQL 扩展可能无论如何都不能接受。