我有2个表格,订单和费率。我想加入这两个表,并选择的OpenTime和closetime之间的最大值和最小值Mysql加入2表并选择日期范围内的最大值和最小值
表1:订单
id type pair lot opentime openprice closeprice closetime
1 buy eurusd 0.01 2016-05-02 02:04:07 1.15112 1.14778 2016-05-02 03:05:00
2 sell gbpusd 0.01 2016-05-02 02:24:17 1.45221 1.44989 2016-05-02 03:05:00
表2:利率
id pair time price
10 eurusd 2016-05-02 03:00:00 1.14522
9 gbpusd 2016-05-02 03:00:00 1.44726
8 eurusd 2016-05-02 02:30:00 1.15258
7 gbpusd 2016-05-02 02:30:00 1.45311
6 eurusd 2016-05-02 02:00:00 1.15051
5 gbpusd 2016-05-02 02:00:00 1.45173
4 eurusd 2016-05-01 01:30:00 1.14258
3 gbpusd 2016-05-02 01:30:00 1.44326
2 eurusd 2016-05-02 01:00:00 1.15751
1 gbpusd 2016-05-02 01:00:00 1.45911
预期结果
id type pair lot opentime openprice closeprice closetime high timehigh low timelow
1 buy eurusd 0.01 2016-05-02 02:04:07 1.15112 1.14778 2016-05-02 03:05:00 1.15258 2016-05-02 02:30:00 1.14522 2016-05-02 03:00:00
2 sell gbpusd 0.01 2016-05-02 02:24:17 1.45221 1.44989 2016-05-02 03:05:00 1.45311 2016-05-02 02:30:00 1.44726 2016-05-02 03:00:00
我试试这个查询,但得到空的结果
没有where子句得到结果不是空SELECT id,type,pair,lot,opentime,openprice,closeprice,closetime,high,timehigh,low,timelow FROM (SELECT id,type,pair,lot,opentime,openprice,closeprice,closetime FROM `order` ORDER BY closetime DESC) table1
JOIN (SELECT MAX(price) as high,time as timehigh,pair as pairhigh FROM `rates` GROUP BY pair) table2 ON table1.pair=table2.pairhigh
JOIN (SELECT MIN(price) as low,time as timelow,pair as pairlow FROM `rates` GROUP BY pair) table3 ON table1.pair=table3.pairlow
WHERE table2.timehigh between table1.opentime and table1.closetime AND table3.timelow between table1.opentime and table1.closetime
尝试查询,但预计不会
SELECT id,type,pair,lot,opentime,openprice,closeprice,closetime,high,timehigh,low,timelow FROM (SELECT id,type,pair,lot,opentime,openprice,closeprice,closetime FROM `order` ORDER BY closetime DESC) table1
JOIN (SELECT MAX(price) as high,time as timehigh,pair as pairhigh FROM `rates` GROUP BY pair) table2 ON table1.pair=table2.pairhigh
JOIN (SELECT MIN(price) as low,time as timelow,pair as pairlow FROM `rates` GROUP BY pair) table3 ON table1.pair=table3.pairlow
结果
id type pair lot opentime openprice closeprice closetime high timehigh low timelow
1 buy eurusd 0.01 2016-05-02 02:14:07 1.15112 1.14778 2016-05-02 03:05:00 1.15751 2016-05-02 02:00:00 1.14258 2016-05-02 02:00:00
2 sell gbpusd 0.01 2016-05-02 03:24:17 1.45221 1.44989 2016-05-02 03:05:00 1.45911 2016-05-02 02:00:00 1.44326 2016-05-02 02:00:00
如何解决这个问题?
谢谢@ inian – pete
是否有一个sqlfiddle? – Strawberry
没有sqlfiddle @strawberry – pete