我有3个实体(Orders、Items和OrderItems)具有以下架构:

                    OrderItems
    Orders      +---------------+
+-----------+   | id (PK)       |     Items
| id (PK)   |==<| order_id (FK) |   +-------+
| createdAt |   | item_id (FK)  |>==| id    |
+-----------+   | createdAt     |   | name  |
                | quantity      |   +-------+
                +---------------+

我需要保留OrderItems的历史记录,这样,如果OrderItem的数量发生更改,我们就可以记录每次连续更改的原始数量。
我的问题是我希望能够为每个订单从表中只选择最近的项目例如:
First two (initial) OrderItems:
    (id: 1, order_id: 1, item_id: 1, createdAt: 2013-01-12, quantity: 10),
    (id: 2, order_id: 1, item_id: 2, createdAt: 2013-01-12, quantity: 10),

Later order items are amended to have different quantities, creating a new row:
    (id: 3, order_id: 1, item_id: 1, createdAt: 2013-01-14, quantity: 5),
    (id: 4, order_id: 1, item_id: 2, createdAt: 2013-01-14, quantity: 15),

我试着问一下:
SELECT oi.* FROM OrderItems oi
WHERE oi.order_id = 1
GROUP BY oi.item_id
ORDER BY oi.createdAt DESC;

我本希望能产生这样的结果:
| id | order_id | item_id | createdAt  | quantity |
+----+----------+---------+------------+----------+
| 3  | 1        | 1       | 2013-01-14 | 5        |
| 4  | 2        | 2       | 2013-01-14 | 15       |

实际制作:
| id | order_id | item_id | createdAt  | quantity |
+----+----------+---------+------------+----------+
| 1  | 1        | 1       | 2013-01-12 | 10       |
| 2  | 2        | 2       | 2013-01-12 | 10       |

目前,我认为仅仅使用createdAt时间戳就足以识别项目的历史记录,但是我可能会转到链接到每个订单项目(链接列表)的上一个项目。如果这样更容易进行这个查询,我将转到那个。

最佳答案

请改为:

SELECT
  oi.*
FROM OrderItems oi
INNER JOIN
(
   SELECT item_id, MAX(createdAt) MaxDate
   FROM OrderItems
   WHERE order_id = 1
   GROUP BY item_id
) o2  ON oi.item_id = o2.item_id
     AND DATE(oi.CreatedAt) = DATE(o2.MaxDate)
ORDER BY oi.createdAt DESC;

SQL Fiddle Demo
这将给你:
| ID | ORDER_ID | ITEM_ID |  CREATEDAT | QUANTITY |
---------------------------------------------------
|  3 |        1 |       1 | 2013-01-14 |        5 |
|  4 |        1 |       2 | 2013-01-14 |       15 |

关于mysql - 选择最近添加的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14337218/

10-11 04:42