I don\'t know quite how to phrase this so please help me with the title as well. :)
I have two tables. Let\'s call them A and B. The
The subquery solution given above is inefficient. The trigger solution is probably best in a mostly-read database, but for the record here's a join approach that will perform better than a subquery:
SELECT a.id, a.xxx, count(*)
FROM a JOIN b ON (b.a_id = a.id)
GROUP BY a.id, a.xxx
If you're using Django ORM you can simply write:
res = A.objects.annotate(Count('b'))
print res[0].b__count # holds the result count