MySQL查询:选择最新结果

时间:2013-01-03 10:34:52

标签: php mysql sql greatest-n-per-group

我有一个包含数据的MySQL表,并希望为进行的特定测试选择最新的条目。

table: research
columns: id (int), projectid (int), test (varchar),
         when (datetime), result (longtext)

行示例:

1, 6, "Test1", 01-01-2013 12:15, "AAAAA"
2, 6, "Test1", 01-01-2013 13:15, "BBBBB"
3, 6, "Test2", 01-01-2013 16:00, "CCCCC"
4, 6, "Test2", 01-01-2013 16:15, "DDDDD"
5, 6, "Test2", 01-01-2013 16:30, "EEEEE"

如果我想要“测试1”的最新结果,我会使用..

SELECT *
FROM research
WHERE projectid=6 AND test='Test1'
ORDER BY when DESC limit 1

但是如何在一个查询中获得单个项目中每个测试的最新结果?我试过了:

SELECT research.*
FROM research INNER JOIN (SELECT MAX(id) AS id
                          FROM research
                          WHERE projectid=".$ProjectId."
                          GROUP BY test) ids
     ON research.id = ids.id
WHERE research.projectid=".$ProjectId

但它没有给我测试的最新结果,它给了我最老的..

6 个答案:

答案 0 :(得分:2)

子查询背后的想法是它为每个项目和测试单独获取最新日期WHEN。然后将结果连接回原始表格。

SELECT  a.*
FROM    research a
        INNER JOIN
        (
            SELECT projectid, test, MAX(`when`) maxDate
            FROM research
            GROUP BY projectid, test
        ) b ON  a.projectid = b.projectid AND
                a.test = b.test AND
                a.`when` = b.maxDate

答案 1 :(得分:1)

您可以WHERE使用IN过滤max(when)日期:

select *
from research r
where r.projectid = 6
   and r.`when` in (select max(`when`)
                   from research
                   group by projectid, test);

请参阅SQL Fiddle with Demo

答案 2 :(得分:1)

试试这个:

SELECT test,when,result
FROM research r1
WHERE when = (SELECT max(when)
            FROM research r2
            WHERE r2.test=r1.test)

答案 3 :(得分:0)

因此,为了获得每个项目的每个测试,具有最大when列的行,您可以使用:

SELECT r.*
FROM research AS r 
  JOIN
    ( SELECT projectid, test, MAX(`when`) AS maxw
      FROM research
      GROUP BY projectid, test
    ) AS m
    ON  m.projectid = r.projectid
    AND m.test = r.test
    AND m.maxw = r.`when` ;

对于单个项目的每个测试(比如项目6):

SELECT r.*
FROM research AS r 
  JOIN
    ( SELECT test, MAX(`when`) AS maxw
      FROM research
      WHERE projectid = 6
      GROUP BY test
    ) AS m
    ON  m.test = r.test
    AND m.maxw = r.`when` 
WHERE r.projectid = 6 ;

(projectid, test, when)上的索引有助于提高上述查询的效率。


答案 4 :(得分:0)

请尝试以下查询。

SELECT `e`.* FROM (
SELECT `r`.*
FROM research `r`
ORDER By `r`.`when`
DESC
)`e`
WHERE `e`.`projectid`= $ProjectId GROUP BY `e`.`test`

我希望这有帮助。

感谢。

答案 5 :(得分:0)

按分区中的测试和按日期排序。使用分析函数。无需在上方/下方进行复杂的查询......