0

我正在尝试查询 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 记录、标准化等一起存储。问题是我不确定以价格加入已售记录的最佳方式。

4

1 回答 1

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 演示

于 2012-07-22T01:30:23.847 回答