如何从django中的两列获取最新时间戳

时间:2014-05-13 07:06:15

标签: python mysql django django-queryset

如何从两列中获取最新时间,例如,我有两个列名start_time_astart_time_b两者都存储值2014-05-13 12:34:34,但我需要从两列中获取最新时间Python Django。我是django查询的新手请帮我摆脱这个问题。

示例表:

+-----+-----------------------+-----------------------+ 
|  id |    start_time_a       |    start_time_b       |
+-----+-----------------------+-----------------------+
|  1  |  2014-05-13 12:34:34  |  2014-05-13 12:41:34  |
|  2  |  2014-05-13 12:40:34  |  2014-05-13 12:40:40  |
|  3  |  2014-05-13 12:20:34  |  2014-05-13 12:46:34  | 
+-----+-----------------------+-----------------------+

我想要这个输出

|  3  |  2014-05-13 12:20:34  |  2014-05-13 12:46:34  | 

因为它具有来自所有时间戳的最新start_time_b

3 个答案:

答案 0 :(得分:1)

为了从两列获得最大值的行,我找到了这个答案并且非常有用

select * from t where (
                      start_time_a in (select greatest(max(start_time_a), max(start_time_b)) from t) or
                      start_time_b in (select greatest(max(start_time_a), max(start_time_b)) from t)
                      );

mysql greatest()函数

答案 1 :(得分:1)

参考SQL you posted,您可以将其放入Django extra() Queryset modifier

qs = YourModel.objects.extra(select={
    'max_time': '''
    select * from t where (
        start_time_a in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        ) or start_time_b in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        )
    )'''
})

# each YourModel object in the queryset will have an extra attribute, max_time
for obj in qs:
    print obj.max_time

答案 2 :(得分:0)

MySQL解决方案

如果要从所有记录中识别最新日期,而不考虑其他列值,可以在日期列上使用MAX函数。

示例

select max( start_time_a ) as mx_start_time_a
       , max( start_time_b ) as mx_start_time_b
from table_name