Updated:
Here is the demo and current result based on M Khalid Junaid's answer. The query still doesn't output my expected result.
I have a very simple table and here is the values.
id animal_id latitude longitude created_at
--------------------------------------------------------------------------
119 75 1.356203 103.828140 2014-04-30 15:00:04
118 75 1.296613 103.857079 2014-04-30 14:58:58
117 75 1.296613 103.857079 2014-04-30 14:58:20
116 75 1.296613 103.857079 2014-04-30 14:53:17
Here is my query and I want to GROUP if latitude, longitude and user_id is same.
select p.id,p.animal_id,p.name,p.latitude,p.longitude,p.created_at from Photo p
where 5 >= (select count(*)
from Photo p2
where p2.animal_id = p.animal_id and
p2.id <= p.id
)
AND DATE(p.created_at) > DATE_SUB(NOW(),INTERVAL 13 DAY)
AND ( p.latitude BETWEEN 0.908862 AND 1.717581 ) AND ( p.longitude BETWEEN 103.584595 AND 104.098206 )
GROUP BY p.latitude,p.longitude,p.animal_id
ORDER BY p.created_at DESC;
Current result id = 116
id animal_id latitude longitude created_at
--------------------------------------------------------------------------
119 75 1.356203 103.828140 2014-04-30 15:00:04
116 75 1.296613 103.857079 2014-04-30 14:53:17
Expected result id = 118
I want to get most recent result when I group latitude,longitude,uer_id
id animal_id latitude longitude created_at
--------------------------------------------------------------------------
119 75 1.356203 103.828140 2014-04-30 15:00:04
118 75 1.296613 103.857079 2014-04-30 14:58:58
I've tried several ways but couldn't get the desired result.