Mysql选择每组内的最新输入

时间:2015-02-10 12:02:24

标签: mysql

所以我把这个表命名为

maid_processing
id     code    confirm_arrival    category_id    arrived 
5       A1     2014-01-02          NULL            1
4       B2     2014-01-02          NULL            1
3       A1     2014-01-01          NULL            1
2       B2     2014-01-01          NULL            1
1       B2     2014-01-01          NULL            0

正如您所看到的,代码会重复,但其他列可能会有所不同。 我想要实现的是我想要

选择confirm_arrival字段满足给定日期范围的所有代码,并且到达= 1,因为A1和B2将重复两次,因为示例满足条件 然后我们可以将具有相同代码的那些组合在一起,因此,形成2组,A1和B2

所以我最终想要的是,在这两个组中,我只希望每个组中的输入行的id号=最大(因此是最新的)。

    The desired result will be 
id   code    confirm_arrival
5    A1      2014-01-02 
4    B2      2014-01-02

到目前为止,我只返回最早的(id =每组中最小的),请参阅下面的代码

SELECT * 
  FROM 
     ( SELECT * 
         FROM maid_processing mp
         LEFT
         JOIN 
            ( SELECT id catid
                   , archived 
                FROM category
            ) AS cat 
           ON cat.catid = maid_mp.category_id 
        WHERE arrived = 1 
          AND (archived IS NULL OR archived = 0) 
          AND confirm_arrival BETWEEN :from_date AND :to_date     
        ORDER 
           BY confirm_arrival DESC
     ) AS inv 
 GROUP 
    BY code;

1 个答案:

答案 0 :(得分:0)

SELECT * 
  FROM 
     ( SELECT * 
         FROM maid_processing mp
         LEFT
         JOIN 
        ( SELECT id catid
               , archived 
            FROM category
        ) AS cat 
       ON cat.catid = mp.category_id 
    WHERE arrived = 1 
      AND (archived IS NULL OR archived = 0) 
      AND confirm_arrival BETWEEN :from_date AND :to_date     
    ORDER 
       BY id DESC
 ) AS inv 
 GROUP 
BY code;

我刚用最后一行的id替换了confirm_arrival。