在日期范围加入MySQL

时间:2012-07-22 00:01:25

标签: mysql join

我正在尝试查询MySQL。假设我有3个表,并想象数据看起来像这样:

apples_sold
+--------+------------+----------+------+
| tranID | date       | apple_id | sold |
+--------+------------+----------+------+
|    101 | 2012-07-01 |      a01 |    2 |
|    102 | 2012-07-02 |      a01 |    5 |
|    103 | 2012-07-03 |      a01 |    1 |
|    104 | 2012-07-04 |      a01 |    0 |
|    105 | 2012-07-05 |      a01 |    2 |
+--------+------------+----------+------+

price_history
+---------+------------+----------+-------+
| priceID | date       | apple_id | price |
+---------+------------+----------+-------+
|     p01 | 2012-07-01 |      a01 | $0.25 |
|     p02 | 2012-07-03 |      a01 | $0.10 | <- price change
+---------+------------+----------+-------+

apple_name
+----------+----------+
| apple_id | name     |
+----------+----------+
|      a01 | McIntosh |
+----------+----------+

尝试创建一个输出此内容的查询:

apple_prices
+------------+----------+-------+
| date       | name     | price |
+------------+----------+-------+
| 2012-07-01 | McIntosh | $0.25 |
| 2012-07-02 | McIntosh | $0.25 |
| 2012-07-03 | McIntosh | $0.10 | <- price change
| 2012-07-04 | McIntosh | $0.10 |
| 2012-07-05 | McIntosh | $0.10 |
+------------+----------+-------+

不想使用apples_sold记录,规范化和全部存储价格。问题是我不确定以价格加入销售记录的最佳方式。

1 个答案:

答案 0 :(得分:5)

您可以使用:

SELECT a.date, d.name, c.price
FROM apples_sold a
INNER JOIN
(
    SELECT a.date, MAX(b.date) AS maxdate
    FROM apples_sold a
    INNER JOIN price_history b ON a.date >= b.date
    GROUP BY a.date
) b ON a.date = b.date
INNER JOIN price_history c ON b.maxdate = c.date
INNER JOIN apple_name d ON a.apple_id = d.apple_id

SQLFiddle Demo