I have different tables in my MYSQL database and I need to create a SELECT query that will check certain values before selecting a row.
It’s basically 3 tables (news, tags and news_tags).
- news contains information about a news.
- tags information about tags.
- news_tags store which tag is used by a news.
Here are my 3 different tables (simplified of course)
To illustrate:
news:
id | status
1 | 1
2 | 1
3 | 0
tags:
tag_id | tag_name
1 | name 1
2 | name 2
news_tags:
id | news_id | tag_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 3 | 1
5 | 3 | 2
Now, at first I wanted to know how many times each tag was being used.
So I came up with this query
SELECT tags.tag_name, news_tags.tag_id, COUNT(*) as count
FROM news_tags
LEFT JOIN tags
ON tags.tag_id = news_tags.tag_id
GROUP BY news_tags.tag_id
ORDER BY count DESC
This give me the following output
tag_name | count
name 1 | 3
name 2 | 2
Now my problem is that I don’t want to count those that the news.status = 0;
So if we look at my example, in the news table the row with the id = 3 has a status = 0.
The count should not take in effect where news_id = 3 in the news_tags table.
Basically the desired output should be
tag_name | count
name 1 | 2
name 2 | 1
Thank you for your help.
You need to join it with
newstable so you can query forstatus