我有一个select语句,在每个“unit”只需要一个结果的情况下返回数千个结果
表
LID unitnumb lat long time unitid shift unit timeon timeoff crew1 crew2 care onduty randid
226733 cgrausam 36.7929227 -76.1340058 2014-11-28 21:41:51 388 pathfinderKZ,CH 22 2014-11-18 09:38:54 2014-11-18 09:38:54 kzavocki cgrausam NULL 1 IdXENPgZ
226730 kzavocki 40.6324391 -74.4208074 2014-11-28 21:41:43 301 pathfinderKAT 22 2014-10-27 14:28:02 2014-10-27 14:28:02 kzavocki admin NULL 1 gIahPbib
226732 kzavocki 40.6324391 -74.4208074 2014-11-28 21:41:43 409 pathfinderKAT 22 2014-11-21 10:33:32 2014-11-21 10:33:32 kzavocki admin NULL 1 JFASXDXC
226735 kzavocki 40.6324391 -74.4208074 2014-11-28 21:41:43 214 Rover-Kathy 26 2014-10-07 08:47:19 2014-10-07 08:47:19 kzavocki admin NULL 1 CLJSZXeW
我有一个select语句返回这些结果:
SELECT *
FROM gpstracking g
LEFT JOIN units u
ON g.unitnumb = u.crew1 OR g.unitnumb = u.crew2
WHERE u.onduty = 1 and time > DATE_SUB(NOW(), INTERVAL 2 HOUR)
ORDER BY time DESC
目前这个select语句完全符合我的要求除了我只需要每个“单位”1个结果,我希望结果是最近的“时间” 所以理想的结果将是
226733 cgrausam 36.7929227 -76.1340058 2014-11-28 21:41:51 388 pathfinderKZ,CH 22 2014-11-18 09:38:54 2014-11-18 09:38:54 kzavocki cgrausam NULL 1 IdXENPgZ
226735 kzavocki 40.6324391 -74.4208074 2014-11-28 21:41:43 214 Rover-Kathy 26 2014-10-07 08:47:19 2014-10-07 08:47:19 kzavocki admin NULL 1 CLJSZXeW
从上面开始 - 如何修改select语句只显示每个“unit”的单个结果
答案 0 :(得分:0)
一种方法是使用变量:
select *
from (select *,
(@rn := if(@u = u.unit, @rn + 1,
if(@u := u.unit, 1, 1)
)
) as seqnum
from gpstracking g LEFT JOIN
units u
on g.unitnumb = u.crew1 or g.unitnumb = u.crew2 CROSS JOIN
(select @u := '', @rn := 0) vars
where u.onduty = 1 and time > DATE_SUB(NOW(), INTERVAL 2 HOUR)
order by u.unit, time desc
) ut
where seqnum = 1
order by time desc;