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

后端 未结 5 1445
我在风中等你
我在风中等你 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: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
    

提交回复
热议问题