Django self join , How to convert this query to ORM query
如何将该查询转换为Django ORM查询。
1 2 3 4 | 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 |
实际上我想根据其他列值获取所有最新值。
例如我的桌子就像-
1 2 3 4 5 6 7 | 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}]
使用更规范的数据模型,您会更轻松地进行此操作。考虑使用这样的方法:
1 2 3 4 5 6 7 | class NodeGroup(model.Model): pass class NodeHealth(model.Model): node_group = models.ForeignKey(NodeGroup, related_name='nodes') health_time = models.IntegerField() status = models.IntegerField() |
然后您可以执行以下操作:
1 2 3 4 5 | from django.db.models import Max, F nodes = NodeHealth.objects.all().annotate( max_health_time=Max('node_group__nodes__health_time') ).filter(health_time=F('max_health_time')) |
不幸的是,此时,如果多个节点的
如果数据库支持分析,则可以执行以下操作:
1 2 3 4 | q = NodeHealth.objects.extra( select={'row_num':"ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2 DESC)"}, where=["row_num=1"] ) |