我有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时间戳应该足以识别项目的历史记录,但是我可能会转移到每个订单项目(链接列表)中的上一个项目。如果这样可以更容易地进行此查询,那么我将转向它。
答案 0 :(得分:3)
请改为尝试:
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;
这会给你:
| ID | ORDER_ID | ITEM_ID | CREATEDAT | QUANTITY |
---------------------------------------------------
| 3 | 1 | 1 | 2013-01-14 | 5 |
| 4 | 1 | 2 | 2013-01-14 | 15 |
答案 1 :(得分:0)
这是另一种解决方案:绝对不要反对Mahmoud:D(感谢sqlfiddle) 如果你想试试。
查询:
SELECT * FROM orderitems
GROUP BY id
ORDER BY createdAt DESC
LIMIT 2
;
结果:
| ID | ORDER_ID | ITEM_ID | CREATEDAT | QUANTITY |
-----------------------------------------------------------------------
| 3 | 1 | 1 | January, 14 2013 02:00:00+0000 | 5 |
| 4 | 1 | 2 | January, 14 2013 02:00:00+0000 | 15 |