1

我尝试编写一个 sql 请求来查找每个组的最后一条记录,这是我的表的布局:

 --------------------------------------
| id | Group | message | Status | date|
 -------------------------------------
| 1  | A     | msg1    | sent   | dt  |
 -------------------------------------
| 2  | A     | msg2    |deferred| dt2 |
 -------------------------------------
| 3  | B     | msg3    |deferred| dt  |
 -------------------------------------
| 4  | B     | msg4    |deferred| dt  |
 -------------------------------------
| 5  | B     | msg5    |Bounced | dt  |
 -------------------------------------
| 6  | C     | msg6    |sent    | dt  |
 -------------------------------------
| 7  | D     | msg7    |deferred| dt  |
 -------------------------------------
| 8  | D     | msg8    |deferred| dt  |
 -------------------------------------
| 9  | D     | msg9    |sent    | dt  |
 -------------------------------------

我试图得到这个输出:

 --------------------------------------
| id | Group | message | Status | date|
 -------------------------------------
| 2  | A     | msg2    |deferred| dt  |
 -------------------------------------
| 5  | B     | msg5    |bounced | dt  |
 -------------------------------------
| 8  | D     | msg8    |deferred| dt  |
 -------------------------------------

这意味着对于每个组,我希望使用我表中的日期最后一个“延迟”或“退回”消息。我从做这个请求开始,但我不知道如何修改它以获得我想要的结果:

SELECT ee.Group, ee.message
FROM email_errors ee
LEFT JOIN email_errors ee2 ON ( ee.Group = ee2.Group
AND ee.id < ee2.id ) 
WHERE ee2.id IS NULL 
AND ee2.status <>0

我注意到 ee.status <> 0 是因为在我的真实表中我替换了 3 个可能的状态 bu 0、1、2,并且我用 0 替换了发送状态。

4

2 回答 2

1

我会做以下事情:

SELECT ee.*
FROM email_errors as ee
CROSS JOIN
(
    SELECT ee.Group as grp, MAX(ee.id) AS max_id
    FROM email_errors as ee
    CROSS JOIN
    (
        SELECT Group as grp, MAX(date_t) AS max_date
          FROM email_errors
          WHERE status <> 0
          GROUP BY Group
    ) aux
    WHERE ee.Group = aux.grp
    AND ee.date_t = aux.max_date
    GROUP BY ee.Group
) outer_aux
WHERE ee.Group = outer_aux.grp
AND ee.id = outer_aux.max_id
于 2013-11-07T15:35:41.453 回答
1

请注意,这group是 MySQL 中的保留字 - 所以对于列来说不是一个好名字......

SELECT x.* 
  FROM email_errors x 
  JOIN 
     ( SELECT email_group
            , MAX(id) max_id 
         FROM email_errors 
        WHERE status IN ('deferred','bounced') 
        GROUP 
           BY email_group
     ) y 
    ON y.email_group = x.email_group 
   AND y.max_id = x.id;
于 2013-11-07T15:49:21.610 回答