简体   繁体   English

Postgres递归查询+分组依据+加入Django

[英]Postgres Recursive query + group by + join in Django

My Requirement is to write a sql query to get the sub-region wise (fault)events count that occurred for the managedobjects. 我的要求是编写一个SQL查询,以获取针对托管对象发生的子区域明智(故障)事件计数。 My database is postgres 8.4. 我的数据库是postgres 8.4。 Let me explain using the table structure. 让我解释一下表结构。

My tables in django: Managedobject: 我在Django中的表格:ManagedObject:

class Managedobject(models.Model):
   name                = models.CharField(max_length=200, unique=True)
   iscontainer         = models.BooleanField(default=False,)
   parentkey           = models.ForeignKey('self', null=True)

Event Table: 活动表:

class Event(models.Model):
    Name        = models.CharField(verbose_name=_('Name'))
    foid        = models.ForeignKey(Managedobject)

Managedobject Records: 被管理对象记录:

NOC
   Chennai
      MO_1
      MO_2
      MO_3
   Mumbai
      MO_4
      MO_5
      MO_6
   Delhi
   Bangalore
IP
   Calcutta
   Cochin

Events Records: 活动记录:

event1 MO_1
event2 MO_2
event3 MO_3
event4 MO_5
event5 MO_6    

Now I need to get the events count for all the sub-regions. 现在,我需要获取所有子区域的事件计数。 For example, 例如,

for NOC region:
  Chennai - 3
  Mumbai - 2
  Delhi - 0
  Bangalore - 0

So far I am able to get the result in two different queries. 到目前为止,我能够通过两个不同的查询获得结果。

  1. Get the subregions. 获取子区域。

     select id from managedobject where iscontainer = True and parentkey = 3489 
  2. For each of the region (using for loop), get the count as follows: 对于每个区域(使用for循环),按如下方式获取计数:

     SELECT count(*) from event ev WHERE ev.foid IN ( WITH RECURSIVE q AS ( SELECT h FROM managedobject h WHERE parentkey = 3489 UNION ALL SELECT hi FROM q JOIN managedobject hi ON hi.parentkey = (qh).id ) SELECT (qh).id FROM q ) 

Please help to combine the queries to make it a single query and for getting the top 5 regions. 请帮助组合查询以使其成为单个查询并获取前5个区域。 Since the query is difficult in django, I am going for a raw sql query. 由于在django中查询很困难,因此我要进行原始sql查询。

I got the query: 我得到了查询:

WITH RECURSIVE q AS ( 
  SELECT  h, 
          1 AS level, 
          id AS ckey, 
          displayname as dname 
  FROM managedobject h 
  WHERE parentkey = 3489  
    and logicalnode=True 

 UNION ALL 

 SELECT  hi, 
         q.level + 1 AS level, 
         ckey, 
         dname 
 FROM q 
   JOIN managedobject hi ON hi.parentkey = (q.h).id 
) 
SELECT count(ckey) as ccount, 
       ckey, 
       dname 
FROM q 
  JOIN event as ev on ev.foid_id = (q.h).id 
GROUP BY ckey, dname 
ORDER BY ccount DESC 
LIMIT 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM