Mysql group by和max值不返回实际的最大值

时间:2015-08-19 23:51:30

标签: mysql group-by having

testid  testid  studyid PRINCIPAL   buildnumber
403      403    1109    2670506       1030716
497      497    1109    2468736       1030716
**495        495    1109    2468736       1030716**
442      442    1109    2468736       1030716

和结果

SELECT c.testid, t.testid, c.studyid, c.PRINCIPAL, t.buildnumber 
FROM comp_max c
INNER JOIN testlog t
ON t.testid = c.testid
WHERE t.buildnumber = 1030716
group by studyid having max(c.testid)

所以我尝试了以下查询来获取max testid(495)

testid  testid  studyid PRINCIPAL   buildnumber
403      403    1109    2670506       1030716

但是返回的值是403 testid,而不是495

class Base
{
    private static Dictionary<string, int> myStaticFieldDict = new Dictionary<string, int>();

    public int MyStaticField
    {
        get
        {
            return myStaticFieldDict.ContainsKey(this.GetType().Name)
                   ? myStaticFieldDict[this.GetType().Name]
                   : default(int);
        }

        set
        {
            myStaticFieldDict[this.GetType().Name] = value;
        }
    }

    void MyMethod()
    {
        MyStaticField = 42;
    }
}

所以预期的结果将是testid 495.你能帮助我解决这个问题吗?或任何提示?

由于

1 个答案:

答案 0 :(得分:0)

我自己使用子查询修复了问题 这是答案

SELECT c.studyid, c.testid, c.PRINCIPAL FROM comp_max c 
WHERE c.testid in (
   SELECT MAX(c.testid) FROM comp_max c
   INNER JOIN testlog t ON t.testid = c.testid
   WHERE c.studyid IN ( 
                    SELECT c.studyid FROM comp_max c 
                    INNER JOIN testlog t
                    ON t.testid = c.testid
                    WHERE t.buildnumber = 1030716 )
   AND t.buildnumber = 1030716
   GROUP  BY c.studyid )
GROUP BY studyid
ORDER BY c.studyid desc

如果您有更好的解决方案,我非常乐意得到您的答案 感谢