加入2个表以查找最接近的时间戳

时间:2016-10-27 11:59:12

标签: mysql

所以我有1个MySQL表,包括销售以及销售的价格和时间。我有一张第二张桌子,每5分钟拍摄一次市场上每件商品的平均价格。这些东西可以每分钟改变价格。

我需要从销售时间和销售之前和之后最接近销售时间的每件商品中获得表2的市场价格。

我一直在尝试将其分为以前的价格和销售后的价格作为2个单独的查询。到目前为止,我所得到的是以下内容。但它的问题是它只在设置行之后命令market.time。我需要它在市场前订购。在GROUP BY语句选择每个sales.id的顶行之前(希望这是有意义的)。基本上它会返回已售出物品的最早价格,然后按这些时间排序整个表格。

SELECT sales.id, sales.price, sales.time, sales.item_id, market.time, market.price,
FROM sales_table sales
INNER JOIN market_table market ON market.item_id = sales.item_id
WHERE market.time < sales.time
GROUP BY sales.id
ORDER BY market.time DESC;

销售表

| id | price|         time                   | item_id  |
--------------------------------------------------------
|  1 |     0.5  | 2006-10-05 11:55:44        | 5        |
|  2 |     1.1  | 2007-10-07 12:34:17        | 5        | 
|  3 |     0.4  | 2008-10-09 08:19:36        | 9        |
|  4 |     5.8  | 2010-10-13 04:28:14        | 1        |

市场表

| id | price|         time                   | item_id  |
--------------------------------------------------------
|  1 |     0.5  | 2006-10-05 11:50:00        | 1        |
|  2 |     1.1  | 2006-10-05 11:55:00        | 1        |
|  3 |     0.4  | 2008-10-09 02:20:00        | 2        |
|  4 |     5.8  | 2010-10-09 04:25:00        | 2        |

期望的结果

| s_id | s_price|      sales_time     | item_id| market_time        |m_price
----------------------------------------------------------------------------
|  1   |   0.5  | 2006-10-05 11:55:44 | 5      | 2006-10-05 11:55:00| 0.5
|  2   |   1.1  | 2007-10-07 12:34:17 | 5      | 2007-10-07 12:30:00| 1.2
|  3   |   0.4  | 2008-10-09 08:19:36 | 9      | 2008-10-09 08:15:00| 0.45
|  4   |   5.8  | 2010-10-13 04:28:14 | 1      | 2010-10-13 04:25:00| 6.0

我目前从上述查询中得到的内容

| s_id | s_price|      sales_time     | item_id| market_time        |m_price
----------------------------------------------------------------------------
|  1   |   0.5  | 2006-10-05 11:55:44 | 5      | 2001-01-01 00:00:00| 1.0
|  2   |   1.1  | 2007-10-07 12:34:17 | 5      | 2002-06-01 09:15:00| 0.8
|  3   |   0.4  | 2008-10-09 08:19:36 | 9      | 2002-08-14 15:30:00| 0.2
|  4   |   5.8  | 2010-10-13 04:28:14 | 1      | 2003-10-01 12:00:00| 5.2

1 个答案:

答案 0 :(得分:0)

请按行号使用。

select id, time, price, time, price from (
    SELECT sales.id, sales.time, sales.price, market.time, market.price, row_number() over (partition by sales.id order by ABS(DATEDIFF(SECOND, market.time, sales.time))) as r
    FROM sales_table sales
    INNER JOIN market_table market ON market.item_id = sales.item_id
) as t
where t.r = 1
ORDER BY market.time DESC;