Question

I have a table of test results with multiple rows per user and multiple users. I want to return a single row for every user with the details from the 'most recent' test they have taken. I had assumed I could do this in CodeIgniter using a combination of order_by and group_by, however using this approach doesn't work as it appears that CI disregards the order_by... :?

$this->db->where('email','email@example.com');
    $this->db->order_by('test_date', 'DESC');
    $this->db->group_by('email');
    $tmp = $this->db->get('test_results');

How can I overcome this without having to resort to an additional query but still be able to return all the data from the 'most recent' test for each user?

Was it helpful?

Solution

Your problem is related to greatest-n-per-group tag you need to get the recent one result per user this should do the trick,first get the maximum date and email and then use self join with two conditions like ON(t.email =tt.email AND t.test_date=tt.test_date)

SELECT t.* FROM 
test_results t
INNER JOIN (
SELECT email,MAX(test_date) test_date FROM test_results GROUP BY email
) tt ON(t.email =tt.email AND t.test_date=tt.test_date)
ORDER BY t.test_date DESC

In CI you can use query function to run raw query

$this->db->query("SELECT t.* FROM 
test_results t
INNER JOIN (
SELECT email,MAX(test_date) test_date FROM test_results GROUP BY email
) tt ON(t.email =tt.email AND t.test_date=tt.test_date)
ORDER BY t.test_date DESC");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top