SQL查询 - 过滤多个匹配的结果

时间:2014-05-29 15:08:54

标签: mysql sql

以下SQL搜索在特定快照编号(snapnum =(63,48,27))链接到以下ID(0,3000042000000,1000019007037)的对象。对象通过

链接
PROG.galaxyId between DES.galaxyId AND DES.lastprogenitorId

此SQL查询(如下)返回符合这些条件的每个对象。

SELECT DES.galaxyId, PROG.galaxyId, PROG.stellarMass, PROG.snapnum 
FROM dbase PROG, dbase DES 
WHERE DES.galaxyId in (0,3000042000000,1000019007037) 
AND PROG.galaxyId between DES.galaxyId AND DES.lastprogenitorId 
AND PROG.snapnum in (63, 48, 27) 
ORDER BY PROG.snapnum DESC

但是,我不希望每个结果。对于(0,3000042000000,1000019007037)中指定的每个DES.galaxyId,我想在(63,48,27)中的每个snapnum返回一个结果(如果有的话)。这个结果必须是最大的,即具有最大PROG.stellarMass的结果。

有人可以建议进行适当的修改以启用此功能吗?谢谢。

警告:无法使用LIMIT

2 个答案:

答案 0 :(得分:0)

SELECT DES.galaxyId, PROG.galaxyId, PROG.stellarMass, PROG.snapnum 
FROM dbase PROG, dbase DES 
WHERE DES.galaxyId in (0,3000042000000,1000019007037) 
AND PROG.galaxyId between DES.galaxyId AND DES.lastprogenitorId 
AND PROG.snapnum in (63, 48, 27) 
ORDER BY PROG.StellerMass DESC, PROG.snapnum DESC
LIMIT 1

答案 1 :(得分:0)

卡尔,我在这里做了一些大的假设,但这可能会让你看到约翰在评论中提出的建议。

SELECT MsM.galaxyId, min(PROG.galaxyID) AS PROGgalaxyID, MsM.maxStellarMass, MsM.snapnum
FROM (SELECT DES.galaxyId, PROG.snapnum, DES.lastprogenitorId, max(PROG.stellarMass) AS maxStellarMass
FROM dbase PROG, dbase DES
WHERE DES.galaxyId in (0,3000042000000,1000019007037) 
    AND PROG.galaxyId between DES.galaxyId AND DES.lastprogenitorId 
    AND PROG.snapnum in (63, 48, 27) 
GROUP BY DES.galaxyId, PROG.snapnum, DES.lastprogenitorId) AS MsM
JOIN dbase PROG on PROG.galaxyId between MsM.galaxyId AND MsM.lastprogenitorId and  PROG.snapnum=Msm.snapnum and PROG.stellarMass=MsM.maxStellarMass
GROUP BY MsM.galaxyId, MsM.maxStellarMass, MsM.snapnum

假设:

  • 每个DES.galaxyId和DES.lastprogenitorId之间有一个PROG.galaxyID
  • 每个PROG.galaxyID都有一个独特的stellarMass,任何其他PROG.galaxyId都不会共享