如何将请求的结果加入另一个 table(添加列)

How to join the result of a request to another table (to add column)

编辑

我有两个 table:etape 和 etapex。

我需要为每个 idEtape(在 table etapex 中)找到最大值 idProjet,然后 link idEtapeidProjet 从 table etape 到 'nomEtapeandlivrable`。

所以我尝试了两种不同的方法:

SELECT etapexprojet.idEtape, idProjet, nometape, livrable
FROM etape, etapexprojet
WHERE etapexprojet.idetape = (SELECT MAX(etape.idetape) FROM etapexprojet )

不幸的是,这就是我得到的:

这是我的另一个 "solution":

第一步是求最大值(我不想用group by):

SELECT EX.idEtape
FROM etapexprojet EX                   
LEFT JOIN etapexprojet EX2       
  ON EX.idprojet = EX2.idprojet 
  AND EX.idetape < EX2.idetape
WHERE EX2.idetape IS NULL

但现在我卡住了,我不知道如何将我从第一个请求中得到的内容加入 table etape。

最后,它应该给我这样的东西:

但是还有 nomEtapelivrable 列...

在此先感谢您的帮助!

这个每组最大 n 问题有多种解决方案。

一个简单的方法是从这个聚合查询开始,它为您提供每个 IdProjet 的最大值 idEtape:

select idProjet, max(idEtape) idEtape from etapex group by idProjet

然后你可以简单地把它和原来的table连接起来:

select e.*, p.idProjet
from etape e
inner join (
    select idProjet, max(idEtape) idEtape from etapex group by idProjet
) p on p.idEtape = e.idEtape

您可以 JOIN etape table 到第一个查询的结果:

SELECT EX.idProjet, E.*
FROM etape E
JOIN etapexprojet EX ON EX.idEtape = E.idEtape              
LEFT JOIN etapexprojet EX2       
  ON EX.idprojet = EX2.idprojet 
  AND EX.idetape < EX2.idetape
WHERE EX2.idetape IS NULL
ORDER BY idProjet

Demo on SQLFiddle

试试这个:

SELECT ET.idEtape, ETX.idProjet, ET.nomEtape, ET.livrable
FROM etape  ET               
LEFT JOIN etapexprojet ETX ON ET.idEtape = ETX.idEtape 
WHERE ETX.idEtape = (SELECT MAX(idEtape) FROM etapexprojet WHERE idProjet = ETX.idProjet);