Select count of rows in another table in a Postgres SELECT statement

后端 未结 5 1449
我在风中等你
我在风中等你 2020-12-23 16:23

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

5条回答
  •  鱼传尺愫
    2020-12-23 16:39

    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
    

提交回复
热议问题