I have a MySQL table with data, and would like to select the most recent entry for a specific test that was conducted.
table: research
columns: id (int), projectid (int), test (varchar),
when (datetime), result (longtext)
Example of rows:
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"
If I want the latest results for “Test 1”, I use..
SELECT *
FROM research
WHERE projectid=6 AND test='Test1'
ORDER BY when DESC limit 1
But how can I get the latest result for each test in a single project, in one query? I tried:
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
But it does not give me the latest result from a test, it gives me the oldest..
The idea behind the subquery is that it separately gets the latest date
WHENfor every projectid and test. The result of which is then joined back on the original table.