如何将2列分组以仅获取唯一行的最新版本?

时间:2015-05-12 12:34:11

标签: mysql sql

Table structure

上面是输出的一部分,我试图只获得FID和SID的最新组合。即FID:1,SID:1

这是我当前的SQL

def mainview(request):
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/private')
    if request.method == 'POST':
        formulario = AuthenticationForm(request.POST)
        if formulario.is_valid:
            usuario = request.POST['username']
            clave = request.POST['password']

            acceso = authenticate(username=usuario, password=clave)
            if acceso is not None:
                if acceso.is_active:
                    login(request, acceso)
                    return HttpResponseRedirect('/privado')
                else:
                    return render_to_response('noactivo.html', context_instance=RequestContext(request))
            else:
                return render_to_response('nousuario.html', context_instance=RequestContext(request))
    else:
        formulario = AuthenticationForm()
    return render_to_response('mainview.html',{'formulario':formulario}, context_instance=RequestContext(request))

按FID和SID分组会产生意外结果,只显示FID = 1且SID = 1的所有行。

任何人都有任何想法?

我的预期结果:

Expected Results

包含示例数据的当前表结构是: '传感器'表

  • [FID] => 9
  • [SID] => 1
  • [日期时间] => 2015-05-04 00:00:00
  • [Sensor1] => 1000
  • [Sensor2] => 100
  • [Sensor3] => 100
  • [电池] => 10

'Location_polygon'表

  • [username] =>朱迪
  • [FID] => 1
  • [SID] => 1
  • [lat1] => 31.446376
  • [long1] => -83.597959
  • [lat2] => 31.443103
  • [long2] => -83.598051
  • [lat3] => 31.442641
  • [long3] => -83.594875
  • [lat4] => 31.44486
  • [long4] => -83.594595
  • [lat5] => 31.446385
  • [long5] => -83.596625
  • [type] => SAND

2 个答案:

答案 0 :(得分:3)

您可以使用

获得所需的设置
select s_lp.* from Location_polygon s_lp
join(
 select fid,sid,max(time_taken) as time_taken from Location_polygon
 group by fid,sid
)x
on x.fid = s_lp.fid and x.sid=s_lp.sid and x.time_taken = s_lp.time_taken

如果你有一些额外的where条件,那么在第一个别名s_lp的末尾添加它们where s_lp.col_name = {some condition}

更新:从评论看来它有两个表,日期在不同的表中,所以查询将是

select s_lp.* from sensors s
join(
 select fid,sid,max(Datetime) as Datetime from sensors
 group by fid,sid
)x
on x.fid = s.fid and x.sid=s.sid and x.Datetime = s.Datetime
join Location_polygon s_lp on s_lp.fid = s.fid and s_lp.sid = s.sid
WHERE s_lp.username = '$username'

答案 1 :(得分:1)

我不确定这是完成此任务的最佳方式,但您可以尝试一下。

SELECT * 
FROM sensors s
JOIN Location_polygon s_lp 
    ON s.FID = s_lp.FID and s.SID = s_lp.SID
WHERE username = '$username' and Datetime = (
    SELECT max(Datetime) FROM sensors)

我的观点是:如果您只想选择最后的组合,则需要获取最后的日期。这可以通过子查询来完成。我们也可以像上面的@Abhik Chakraborty那样使用FID和SID的INNER JOIN来消除笛卡尔和重复。