简体   繁体   中英

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. My database is postgres 8.4. Let me explain using the table structure.

My tables in 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:

     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. Since the query is difficult in django, I am going for a raw sql query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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