我有一个表活动:
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
我必须连续选择所有 ip 和其他数据,但仅限于 last_active 最高的位置。所以结果应该是这样的:
3 3000 user3 192.168.10.30 6 6000 user2 192.168.10.20 7 7000 user1 192.168.10.10
我尝试过使用:
ORM::factory('Activity')->order_by('last_active','DESC')->group_by('ip')->find_all();
结果是:
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" )
如您所见,我有不同的ips,但 last_active 值不正确。 任何的想法?纯SQL语句或DB :: select()答案是可以的: - )
答案 0 :(得分:0)
怎么样
select id, last_active, login, ip
from activities
where (last_active, ip) in (select max(last_active), ip from activities group by ip )
答案 1 :(得分:0)
使用DB::expr()。以下内容应该有效:
ORM::factory('Activity')
->where(
DB::expr(
'`last_active`,`ip`'
),
'IN',
DB::expr(
'select max(`last_active`), `ip` from `activities` group by `ip`'
)
->find_all();