我尝试编写一个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&lt;&gt; 0因为在我的真实表中我替换了3个可能的状态bu 0,1,2,并且我将发送状态替换为0。
答案 0 :(得分: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
答案 1 :(得分: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;