我的 MYSQL 数据库中有不同的表,我需要创建一个 SELECT 查询来在选择行之前检查某些值。
它基本上是 3 个表(news、tags 和 news_tags)。
- news 包含有关新闻的信息。
- 关于标签的标签信息。
- news_tags 存储新闻使用的标签。
这是我的 3 个不同的表格(当然是经过简化的)
举例说明:
新闻:
id | status
1 | 1
2 | 1
3 | 0
标签:
tag_id | tag_name
1 | name 1
2 | name 2
新闻标签:
id | news_id | tag_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 3 | 1
5 | 3 | 2
现在,起初我想知道每个标签被使用了多少次。 所以我想出了这个查询
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
这给了我以下输出
tag_name | count
name 1 | 3
name 2 | 2
现在我的问题是我不想计算那些 news.status = 0
;
因此,如果我们看一下我的示例,在 news
表中,id = 3
的行有一个 status = 0
。
count
不应在 news_tags
表中的 news_id = 3
生效。
基本上期望的输出应该是
tag_name | count
name 1 | 2
name 2 | 1
感谢您的帮助。
最佳答案
您需要将它与 news
表连接起来,以便您可以查询 status
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
LEFT JOIN news
ON news.id = news_tags.news_id
WHERE news.status = 1
GROUP BY news_tags.tag_id
ORDER BY count DESC
关于mysql - 复杂的MYSQL select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869662/