我有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