SQL Query返回最近一行的另一个过滤器

时间:2015-02-05 03:15:52

标签: mysql sql

我正试图运行某个查询。

这是表结构 -

+--------+----------+--------+
| caseID | status   | update | 
+--------+----------+--------+
     1       New      3-4-2013
     1       Open     3-5-2013
     2       New      3-5-2013
     3       Closed   3-5-2013

我希望我的查询返回最近的行,然后只显示status ='New'的行,即在示例数据中只返回行caseID = 2。

我有这个查询

SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo GROUP BY caseID

该查询返回每个caseID的最新行。现在我很震惊地只显示status ='New'的部分。

我试过这个并得到#1064 SQL错误

`SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo GROUP BY caseID WHERE status = 'New'

我尝试了这个并返回status ='New'的所有行,即使它们不是最新的。这不是我想要的。

SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo WHERE status = 'New' GROUP BY caseID

我提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效。

select * from data
  join (select caseId, max(`update`) as 
           `update` from data 
           where status = 'New' 
           group by caseId) as filter
     on filter.caseId = data.caseId and filter.`update` = data.`update`
where data.status = 'New'
  group by data.caseId;

基本上,您已将表格加入到自身,但内部联接正在识别您尝试检索的最新记录。

Link to SQL Fiddle

答案 1 :(得分:1)

使用group by查找最近一行的日期,然后join并过滤:

select s.*
from structure s join
     (select caseId, max(update) as maxupdate
      from structure s
      group by caseid
     ) ss
     on s.caseId = ss.caseId and s.update = ss.maxupdate
where s.status = 'New';