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
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 = (q.h).id ) SELECT (q.h).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 raw sql query.
Thanks, Siva
iscontainer
field? if parentkey = None then the object isn't a container and if the Managedobject has a parentkey, then it is a container? – DTing Apr 14 '11 at 9:25