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

后端 未结 5 1443
我在风中等你
我在风中等你 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
    SELECT A.*, (SELECT COUNT(*) FROM B WHERE B.a_id = A.id) AS TOT FROM A
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 16:42

    To answer my own question:

    SELECT a.id, a.other_column, ..., 
    (SELECT COUNT(*) FROM b where b.a_id = a.id) AS b_count
    FROM a;
    
    0 讨论(0)
  • 2020-12-23 16:48

    I think the comment by @intgr in another answer is so valuable I'm putting forward this as an alternate answer as this method allows you to filter the calculated column efficiently.

    SELECT
      a.*,
      COUNT(b.id) AS b_count
    
    FROM a
    INNER JOIN b on b.a_id = a.id
    WHERE a.id > 50 AND b.ID < 100 -- example of filtering joined tables, optional
    
    GROUP BY a.id
    HAVING COUNT(b.id) > 10 -- example of filtering calculated column, optional
    ORDER BY a.id
    
    0 讨论(0)
  • 2020-12-23 17:06

    Accepted answer is inefficient (slow) based on my tests. The subquery of table B executing for every row of table A. I'm using following approach based on grouping and joining. It works much faster:

    SELECT A.id, QTY.quantity FROM A
    LEFT JOIN
        (SELECT COUNT(B.a_id) AS quantity, B.a_id FROM B GROUP BY B.a_id) AS QTY
    ON A.id = QTY.a_id
    

    Another variant:

    SELECT A.id, COUNT(B.a_id) AS quantity FROM A
    LEFT JOIN B ON B.a_id = A.id
    GROUP BY A.id
    
    0 讨论(0)
提交回复
热议问题