CodeIgniter Forums
Get last two records from table using active records - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Get last two records from table using active records (/showthread.php?tid=49557)



Get last two records from table using active records - El Forum - 02-24-2012

[eluser]ibnclaudius[/eluser]
How can I get the last two records from a table?

For example I have this:

id | update
1 | a
2 | b
3| c
4 | d
5 | e

I want to return it like this:

4 | d
5 | e

with order_by(id, 'DESC'), it returns:

5 | e
4 | d

How can I do this with active records?



Get last two records from table using active records - El Forum - 02-24-2012

[eluser]CroNiX[/eluser]
I think in that case it would be much easier and simpler to just run array_reverse() on the returned result.


Get last two records from table using active records - El Forum - 02-24-2012

[eluser]ibnclaudius[/eluser]
Thanks! Worked!




Get last two records from table using active records - El Forum - 02-24-2012

[eluser]rip_pit[/eluser]
in mysql you can use something like :

Code:
(SELECT t1.* FROM (SELECT t2.* FROM table2 AS t2 ORDER BY t2.id DESC LIMIT 2) AS t1 ORDER BY t1.id ASC)

Using AR, this should works :

Code:
($this->db->query("(SELECT t1.* FROM (SELECT t2.* FROM table2 AS t2 ORDER BY t2.id DESC LIMIT 2) AS t1 ORDER BY t1.id ASC)");




Get last two records from table using active records - El Forum - 02-24-2012

[eluser]CroNiX[/eluser]
Which will take more memory and resources than just reversing the simple array. Run an explain on that to see. Also, that isn't an active record query, that's a straight up query.


Get last two records from table using active records - El Forum - 02-25-2012

[eluser]rip_pit[/eluser]
i know but it's a pure mysql oriented query without need of php that can sometimes helpfull
ibnclaudius can choose the one that feet best his needs Wink