繁体   English   中英

MySQL-针对一系列列选择不同的值

[英]MySQL - select distinct values against a range of columns

下表将存储一段时间内各种货币之间的汇率:

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_fromcurrency_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之间的最新汇率

以下查询应该工作:

SELECT ce.*
FROM currency_exhcnage ce
LEFT JOIN currency_exchange newer
    ON (newer.currency_from = ce.currency_from
    AND newer.currency_to = ce.currency_to
    AND newer.exchange_date > ce.exchange_date)
WHERE newer.id IS NULL

进行自我LEFT JOIN的技巧是避免诉诸子查询,如果您有大量数据集,子查询可能会非常昂贵。 它实际上是在寻找不存在“较新”记录的记录。

或者,您可以选择一个更简单的方法(尽管它可能(或可能不会,如注释中所述)较慢):

SELECT *
FROM currency_exchange ce
NATURAL JOIN (
    SELECT currency_from, currency_to, MAX(exchange_date) AS exchange_date
    FROM currency_exchange
    GROUP BY currency_from, currency_to
) AS most_recent

在动态查询中插入$ currency_from和$ currency_to的值。 下面的查询将返回最接近当前时间的行

SELECT id FROM currency_exchange WHERE currency_from='$currency_from' AND currency_to='$currency_to' ORDER BY ABS( DATEDIFF( exchange_date, now() ) ) LIMIT 1 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM