2

我有 3 个具有以下架构的实体(订单、项目和订单项目):

                    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 时间戳就足以识别项目的历史记录,但是我可能会转向从每个订单项目(链表)链接到前一个项目。如果这样可以更轻松地进行此查询,我将继续进行。

4

2 回答 2

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;

SQL 小提琴演示

这会给你:

| ID | ORDER_ID | ITEM_ID |  CREATEDAT | QUANTITY |
---------------------------------------------------
|  3 |        1 |       1 | 2013-01-14 |        5 |
|  4 |        1 |       2 | 2013-01-14 |       15 |
于 2013-01-15T12:01:23.770 回答
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 |
于 2013-01-15T12:39:56.217 回答