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

时间:2011-04-14 07:48:36

标签: django postgresql recursion sql

我的要求是编写一个sql查询来获取为managedobjects发生的子区域明智(故障)事件计数。我的数据库是postgres 8.4。让我解释一下使用表结构。

我在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)

活动表:

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

Managedobject记录:

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

活动记录:

event1 MO_1
event2 MO_2
event3 MO_3
event4 MO_5
event5 MO_6    

现在我需要获取所有子区域的事件计数。例如,

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

到目前为止,我能够在两个不同的查询中获得结果。

  1. 获取子区域。

    select id from managedobject where iscontainer = True and parentkey = 3489
    
  2. 对于每个区域(使用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 = (q.h).id 
        ) 
        SELECT (q.h).id FROM q
    )
    
  3. 请帮助组合查询以使其成为单个查询并获取前5个区域。由于django中的查询很困难,我将进行原始的SQL查询。

1 个答案:

答案 0 :(得分:0)

我收到了查询:

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