mysql - 复杂的MYSQL select

标签 mysql sql select

我的 MYSQL 数据库中有不同的表,我需要创建一个 SELECT 查询来在选择行之前检查某些值。

它基本上是 3 个表(news、tags 和 news_tags)。

  1. news 包含有关新闻的信息。
  2. 关于标签的标签信息。
  3. 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 = 0count 不应在 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/

相关文章:

文件名中带有空格的 sqlcmd 脚本

mysql - SQL 连接多次?

html - iPad IOS html 表单选择在触摸时无法打开

select - 读取 COBOL 中的 STDIN (SYSIN)

php - MySQL连接查询在输出中重复用户

mysql - 处理许多列的数据库

php - 如何通过简单的代码使 PHP 输入法(get 和 post)安全?

php - 上传图片并使它们与我的帖子一起显示

sql - 在 SQL 中的字符串中查找不匹配的大括号

sql [db2] 带条件的选择语句