Skip to content
Advertisement

Get counts of rows for each joined table for each row in the main table

I have three tables in my database. The central table in the star schema is sendings with a PK column called id. Each sending record can have zero or more rows in the tables opens.

Similarly, a third table called clicks have the following association to the sending table (one sending can have zero or more clicks):

Both opens and clicks tables have their unique id column, called id. What I would like to have in one query, is the count of all associated opens and clicks for each sending. The following query does not seem to meet that demand.

Advertisement

Answer

The simple solution is to use count(distinct):

count() just counts the number of non-NULL values.

In general, a more performance solution is either correlated subqueries or aggregation before the join:

Note that the outer group by is not necessary in this case.

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