Skip to content
Advertisement

Get count of foreign key from multiple tables

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 B & C.

Output desired (just the id from A & total count in B & C) :

SQL so far SQL Fiddle :

The query I wrote fetches from B & C and counts the occurrences. But if the key doesn’t occur in B or C, it doesn’t show up in the output (e.g. id=2 in output). How can I start my selection from table A & join/union B & C to get the desired output

Advertisement

Answer

If the query involves large parts of b and / or c it is more efficient to aggregate first and join later.
I expect these two variants to be considerably faster:

You need to account for the possibility that some a_id are not present at all in a and / or b. count() never returns NULL, but that’s cold comfort in the face of LEFT JOIN, which leaves you with NULL values for missing rows nonetheless. You must prepare for NULL. Use COALESCE().

Or UNION ALL a_id from both tables, aggregate, then JOIN:

Probably slower. But still faster than solutions presented so far. And you could do without COALESCE() and still not loose any rows. You might get occasional NULL values for bc_ct, in this case.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement