【发布时间】:2014-12-26 12:22:24
【问题描述】:
如何将此查询转换为 django ORM 查询。
select T.node_id, ht, status, data from (
select id, Max(health_time) as ht, node_id from remote_sense_nodehealth group by node_id
) as T
join remote_sense_nodehealth on remote_sense_nodehealth.health_time=T.ht and remote_sense_nodehealth.node_id = T.node_id
其实我想根据其他列的值获取所有最新的值。
例如我的表是这样的 -
c1 | c2 | c3
- - - - - - -
x | 1 AM | d1
x | 2 AM | d2
x | 3 AM | d3
y | 1 AM | d4
y | 2 AM | d5{
期望的输出:
[{c1: x, c2: 3AM, c3: d3}, {c1: y, c2: 2AM, c3: d5}]
【问题讨论】:
-
这里为什么需要自行加入?理论上,分组和每组的最大值就足够了。
-
我尝试使用 values('node_id') 并在 Max(Node_health) 处进行注释,但无法获取其他字段,即该表的“数据”。如果添加值,它也会在该字段上分组。
-
部分原因是从已分组的行中获取“其他”字段通常没有意义
标签: python mysql django django-orm