简体   繁体   中英

Using order_by and group_by in CodeIgniter not working as expected

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM