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

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

提交回复
热议问题