0

我有一张桌子和一个关系

我可能有 10 个提交,但是当我查询数据库时,我只想获取具有唯一 CaseId 的那些,而要返回的应该是具有最新日期的那个。是否可以(并且建议)在单个查询中执行此操作,还是应该在我获取数据的 asp.nets 代码中进行过滤?

编辑:新图像

在此处输入图像描述 在此处输入图像描述

在这里您可以看到我显示了许多具有相同案例 id 的项目,我只想显示最新的一个(基于日期)

这是我当前的 sql 查询

SELECT Submission.Id, Date, center.Name as CenterName, center.Id as CenterId, subject.Name as SubjectName, subject.Id as SubjectId, EmployeeName, Reason, Description, Explanation, Done, ChiefLevel, Action, CaseId 
                    FROM Submission, subject, center
                    WHERE center.Id=CenterId AND subject.Id=SubjectId
                    ORDER BY Date DESC;
4

2 回答 2

2
SELECT caseid 
FROM 
( 
SELECT caseid, max(date) AS max_date 
FROM submission 
GROUP BY caseid 
) a 
JOIN subject t ON a.subjectid=t.id
于 2012-06-25T09:36:37.487 回答
0

我的 QUERY 最终变成了这个

SELECT s.Id, s.Date, c.Name as CenterName, c.Id as CenterId, su.Name as SubjectName, su.Id as SubjectId, s.EmployeeName, s.Reason, s.Description, s.Explanation, s.Done, s.ChiefLevel, s.Action, s.CaseId
                    FROM submission as s
                      INNER JOIN 
                      ( 
                        SELECT CaseId, MAX(Date) AS MaxDateTime 
                          FROM submission 
                        GROUP BY CaseId 
                      ) as groupeds 
                      ON  s.CaseId = groupeds.CaseId 
                      AND s.`Date` = groupeds.MaxDateTime 
                      INNER JOIN
                      (
                        SELECT Id, Name 
                          FROM subject
                      ) as su 
                      ON su.Id=SubjectId
                      INNER JOIN 
                      (
                        SELECT Id, Name 
                          FROM center
                      ) as c 
                      ON c.Id=CenterId;
于 2012-06-27T14:49:58.933 回答