2

我有一个包含数据的 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

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

4

6 回答 6

2

子查询背后的想法是它分别获取WHEN每个 projectid 和测试的最新日期。然后将其结果连接回原始表。

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
于 2013-01-03T10:37:04.640 回答
1

您可以在日期上使用WHERE带有IN该过滤器的a: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

于 2013-01-03T10:40:29.150 回答
1

试试这个:

SELECT test,when,result
FROM research r1
WHERE when = (SELECT max(when)
            FROM research r2
            WHERE r2.test=r1.test)
于 2013-01-03T11:13:22.080 回答
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` ;

对于单个项目的每个测试(比如 project 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)将有助于提高上述两个查询的效率。


于 2013-01-03T10:40:16.763 回答
0

请尝试以下查询。

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

我希望这有帮助。

谢谢。

于 2013-01-03T10:40:41.213 回答
0

分区内按测试分区和按日期排序。使用分析函数。不需要上面/下面的复杂查询......

于 2013-01-03T13:52:07.357 回答