MySQL MAX函数用于不使用GROUP BY子句的类别

时间:2016-07-07 00:32:33

标签: mysql sql max

我在弄清楚如何在MySQL中编写正确的代码时遇到了很多麻烦。

这是我到目前为止所拥有的......

SELECT ProjectSteps.ProjectID, ProjectSteps.StepID, Step.StepName, Step.Definition 
FROM ProjectSteps, Step 
WHERE ProjectSteps.ProjectID = 
    (SELECT MAX(ProjectSteps.StepID) OVER ProjectSteps.ProjectID 
     FROM ProjectSteps 
     WHERE ProjectSteps.ProjectID IN (1, 2, 3) 
     )
ORDER BY ProjectSteps.ProjectID;

对于我的查询,我有2个表

STEP (StepId, StepName, Definition)

ProjectSteps (StepID, ProjectId, StartingDate, EndingDate)

我必须同时获得每个项目的最后一步的步骤名称和步骤定义。

如:

Project ID  StepId   StepName  Definition

我不能使用GROUP BY子句:(

希望有人能说得对!

1 个答案:

答案 0 :(得分:0)

我仍然不确定为什么你不能使用group by,但这是使用correlated subquery的另一个选项:

select ps.projectid, s.stepid, s.stepname, s.definition
from projectsteps ps 
  join step s on ps.stepid = s.stepid
where ps.projectid in (1,2,3)
  and s.stepid = (select stepid
                  from projectsteps ps2 
                  where ps.projectid = ps2.projectid
                  order by ps2.stepid desc
                  limit 1)