以下查询准确地返回值w.price
但是w.time
被赋予2017-11-23 15:12:00
,这不是返回行中的正确值。但是,它始终与WHERE time >=
子句匹配。造成这种情况的原因是什么?
SELECT
history.pair_id,
MIN(history.price) as all_time_low,
history.time as all_time_low_time,
w.price as one_week_price,
w.time as one_week_time
FROM ep_ex_waex history
INNER JOIN (
SELECT MIN(price) as price, time, pair_id
FROM ep_ex_waex
WHERE pair_id = 2
AND time >= '2017-11-23 15:12:00'
) as w ON w.pair_id = history.pair_id
结果
+---------+--------------+---------------------+----------------+---------------------+
| pair_id | all_time_low | all_time_low_time | one_week_price | one_week_time |
+---------+--------------+---------------------+----------------+---------------------+
| 2 | 392.3 | 2017-11-23 12:11:00 | 396.77 | 2017-11-23 15:12:00 |
+---------+--------------+---------------------+----------------+---------------------+
列all_time_low_time
不正确。
ep_ex_waex结构
CREATE TABLE `ep_ex_waex` (
`id` int(11) NOT NULL,
`pair_id` int(11) DEFAULT NULL,
`price` double NOT NULL,
`volume` double NOT NULL,
`time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
答案 0 :(得分:0)
也许这个mod会关注结果,使用WHERE来定位基于pair_id和MIN的价格。
SELECT price, time, pair_id
FROM ep_ex_waex ep
WHERE pair_id = 2
AND time >= '2017-11-23 15:12:00'
AND price = (SELECT min(price) FROM ep_ex_waex WHERE pair_id=ep.pair_id);
您的完整查询如下所示:
SELECT
history.pair_id,
MIN(history.price) as all_time_low,
history.time as all_time_low_time,
w.price as one_week_price,
w.time as one_week_time
FROM ep_ex_waex history
INNER JOIN (
SELECT price, time, pair_id
FROM ep_ex_waex ep
WHERE pair_id = 2
AND time >= '2017-11-23 15:12:00'
AND price = (SELECT MIN(price) FROM ep_ex_waex eps WHERE eps.pair_id=ep.pair_id)
) as w ON w.pair_id = history.pair_id;
如果不使用这么多的subqueris,它可能会被优化很多,但希望你能得到这个想法。
祝你好运。=== TEST CASE === 使用的数据:
+-------+---------------------+---------+
| price | time | pair_id |
+-------+---------------------+---------+
| 1.29 | 2017-11-23 15:12:00 | 2 |
| 1.19 | 2017-11-24 15:12:00 | 2 |
| 1.79 | 2017-11-25 15:12:00 | 2 |
+-------+---------------------+---------+
查询:
mysql-sql> SELECT price, time, pair_id
FROM ep_ex_waex ep
WHERE pair_id = 2
AND time >= '2017-11-23 15:12:00'
AND price = (SELECT MIN(price) FROM ep_ex_waex eps WHERE eps.pair_id=ep.pair_id);
+-------+---------------------+---------+
| price | time | pair_id |
+-------+---------------------+---------+
| 1.19 | 2017-11-24 15:12:00 | 2 |
+-------+---------------------+---------+
看起来对我来说,找到了中间记录,最低价格和匹配日期。将您的查询分解为细分,看看是否可以使其正常工作。