Get count of foreign key from multiple tables

前端 未结 3 1014
滥情空心
滥情空心 2021-01-18 17:39

I have 3 tables, with Table B & C referencing Table A via Foreign Key. I want to write a query in PostgreSQL to get all ids from A and also their total occurrences from

3条回答
  •  长情又很酷
    2021-01-18 18:19

    Use left join with a subquery:

    SELECT a.id, COUNT(x.id)
    FROM a
    LEFT JOIN (
        SELECT id, a_id FROM b
        UNION ALL
        SELECT id, a_id FROM c
    ) x ON (a.id = x.a_id)
    GROUP BY a.id;
    

提交回复
热议问题