Skip to content
Advertisement

Multiple select statements in single query while using ‘group by’ and ‘join’

I have three tables –

podcasts, videos and others.

Each of the entities under these are associated with a category and subcategories.

Example for podcasts –

enter image description here

This category_id and subcategory_id have their name values in their respective tables –

enter image description here enter image description here

Now, I want to get the count of podcasts, videos and text under each category & subcategory combination. My individual SQL query are these –

For podcasts

For others

And similar one for videos

Now, I want to combine them into a single query so that I get three columns for counts in a single result – podcast_count, other_count and videos_count. How do I do that?

Advertisement

Answer

Join the CROSS join of categories to sub_categories, so you get all the combinations of categories and subcategories, to the other 3 tables with LEFT joins and group by each combination and aggregate:

The WHERE clause filters out any combination of category and subcategory that does not contain any podcast, video or other link.

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