I’m wondering all day and I cant get it done.
I have a simple test table with news system as example. We have news, tags, and categories.
News can have many tags and one category. What I need is to count how many news are under each tag in each category. For example we could have 4 news with general tag under politics category and 2 news with general tag under science category.
My tables looks like this:
news:
- news_id
- category_id
- title
categories:
- category_id
- category_name
tags:
- tag_id
- tag_name
news_tags:
- news_id
- tag_id
Here is a simple MindMap to clarify what I need:

https://i.stack.imgur.com/6ySiJ.png
Here is a query I’ve tried with no success:
SELECT *, COUNT(n.news_id) AS news_count FROM news AS n
LEFT JOIN categories AS c ON n.category_id = c.category_id
LEFT JOIN news_tags AS tn ON n.news_id = tn.news_id
LEFT JOIN tags AS t ON tn.tag_id = t.tag_id
GROUP BY t.tag_id, c.category_id;
Your query works without errors for me.
What error do you get when you run your query/Why is it no success?
This is my attempt to set up your situation:
Result of your query:
However it doesn’t make sense to
SELECT *since you’re aggregating counts by tag/category and things liketitledon’t make sense when aggregated.You might try:
To get: