I have a table activities :
id last_active login ip 1 1000 user1 192.168.10.10 2 2000 user2 192.168.10.20 3 3000 user3 192.168.10.30 4 4000 user1 192.168.10.10 5 5000 user2 192.168.10.20 6 6000 user2 192.168.10.20 7 7000 user1 192.168.10.10
I have to select all ip and other data in a row, but only where last_active is the highest. So the result should like that:
3 3000 user3 192.168.10.30 6 6000 user2 192.168.10.20 7 7000 user1 192.168.10.10
I've tried it by using:
ORM::factory('Activity')->order_by('last_active','DESC')->group_by('ip')->find_all();
and the result is:
array(4) ( "id" => string(1) "3" "last_active" => string(4) "3000" "login" => string(5) "user3" "ip" => string(13) "192.168.10.30" ) array(4) ( "id" => string(1) "2" "last_active" => string(4) "2000" "login" => string(5) "user2" "ip" => string(13) "192.168.10.20" ) array(4) ( "id" => string(1) "1" "last_active" => string(4) "1000" "login" => string(5) "user1" "ip" => string(13) "192.168.10.10" )
As you can see, I have distinct ips but the last_active value is not correct. Any idea? Pure SQL statement or DB::select() answer is OK :-)
how about
select id, last_active, login, ip
from activities
where (last_active, ip) in (select max(last_active), ip from activities group by ip )
Use DB::expr() . Something like the following should work:
ORM::factory('Activity')
->where(
DB::expr(
'`last_active`,`ip`'
),
'IN',
DB::expr(
'select max(`last_active`), `ip` from `activities` group by `ip`'
)
->find_all();
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.