Skip to content
Advertisement

Count from 4 tables with join and null values

Tables:

What I am expecting to query is this:

However this is what I get:

With this query:

I wonder, in what way the query above could be modified to return the expected results? What would be a good approach to achieve this?

Advertisement

Answer

You are joining along two dimensions, so you are getting a Cartesian products. That is simply what happens.

A hacky solution — which works quite well if there are not too many comments and likes for a given post — is to use COUNT(DISTINCT):

The most efficient solution, though, is probably correlated subqueries:

This is faster because it avoids the outer aggregation. However, it requires indexes on comments(post_id) and likes(post_id).

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