我有 3 个实体(订单、商品和 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/