MySQL-查询以获取具有特定列的唯一值的前2条记录

时间:2019-02-07 19:24:20

标签: mysql sql

我有一个记录和处理产品订单的应用程序。从最初创建订单的时间到最终提交履行该订单的过程,在此过程中,一名或多名员工可能会对其1个或多个属性进行1次或多次更改。我将订单号和启动订单的员工存储在1个表中,然后将所有订单的所有更改(包括启动详细信息)存储在另一个表中。像这样:

订单

ORDER_ID   EMPLOYEE
1          dan
2          dan
3          fred

Order_Activity

ACTIVITY_ID    ORDER_ID    UPDATER    DATE      QTY    SIZE    COLOR    STATUS
1               1          dan        1/1/2017  5      m       red      new
2               1          dan        1/3/2017  15     m       red      updated
3               1          tom        1/9/2017  15     l       red      submitted
4               2          dan        1/1/2017  25     l       blue     new
5               2          tom        1/1/2017  25     l       blue     submitted
6               3          fred       1/9/2017  15     s       red      new
7               3          fred       1/10/2017 5      l       red      updated
8               3          fred       1/11/2017 5      m        red     updated
9               3          tom        1/11/2017 5      m        red     submitted

我需要向发起订单的员工显示两个最近的订单,以及状态更改为“已提交”时的订单属性(数量,大小和颜色)。

如果我只需要一个订单(最新订单),我想我可以使用:

SELECT 
    Orders.EMPLOYEE, 
    Order_Activity.QTY, 
    Order_Activity.SIZE,
    Order_Activity.COLOR FROM Orders 
        INNER JOIN Order_Activity 
            ON Orders.ORDER_ID = Order_Activity.ORDER_ID 
            ORDER BY Order_Activity.date DESC LIMIT 1

但是,我很难想象如何找到ORDER_ID具有不同值的下一条记录,同时将所有记录保留在一个查询中。

任何人都可以通过查询帮助我生成类似以下内容的信息(基于上面提供的数据):

ORDER_ID    EMPLOYEE    QTY    SIZE    COLOR
3           fred        5      m       red
1           dan         15     l       red

还是不能在1个查询中完成?

2 个答案:

答案 0 :(得分:1)

您可以对最大日期组da order_id使用内部联接与子查询

select o.ORDER_ID, o.EMPLOYEE , oa.QTY, oa.SIZE, oa.SIZE
from Orders o 
inner join  Order_Activity oa on o.ORDER_ID = oa.ORDER_ID 
inner join  (
  select  ORDER_ID, max(date) max_date
  from Order_Activity
  group by ORDER_ID 
) tt on tt.ORDER_ID = o.ORDER_ID 
    and tt.max_date = oa.date

答案 1 :(得分:0)

如果您拥有MS SQL,那么我应该向您建议下一个查询:

WITH prepare AS
(
SELECT 
     Orders.EMPLOYEE
    , Order_Activity.QTY
    , Order_Activity.SIZE
    , Order_Activity.COLOR
    , ROW_NUMBER() OVER (PARTITION BY Orders.ORDER_ID ORDER BY Order_Activity."date") AS rnbr
FROM Orders 
        INNER JOIN Order_Activity 
            ON Orders.ORDER_ID = Order_Activity.ORDER_ID 
)
SELECT

prepare.EMPLOYEE
, prepare.QTY
, prepare.SIZE
, prepare.COLOR

FROM prepare
WHERE prepare.nmbr = 1

WITH prepare AS ( SELECT Orders.EMPLOYEE , Order_Activity.QTY , Order_Activity.SIZE , Order_Activity.COLOR , ROW_NUMBER() OVER (PARTITION BY Orders.ORDER_ID ORDER BY Order_Activity."date") AS rnbr FROM Orders INNER JOIN Order_Activity ON Orders.ORDER_ID = Order_Activity.ORDER_ID ) SELECT prepare.EMPLOYEE , prepare.QTY , prepare.SIZE , prepare.COLOR FROM prepare WHERE prepare.nmbr = 1

您可以在My SQL中尝试使用此语句,因为该查询会执行标准SQL。