【问题标题】:SELECT and ORDER BY that column using COUNT from another table使用另一个表中的 COUNT 对该列进行 SELECT 和 ORDER BY
【发布时间】:2013-05-02 13:59:06
【问题描述】:

我的情况是这样的:

我有 3 个表,其结构如下:

articles: article_id, more data;
tags: tag_id, tag_name, more data;
article_tags: article_tag_id, tag_id, article_id

每篇文章可以有多个标签。我想检索一篇文章的标签(提供了article_id),按该标签的总使用次数排序。

例如:

Article1 has tags 'tag4', 'tag3', 'tag2'
Article2 has tags 'tag4', 'tag3'
Article3 has tags 'tag4'
Article4 has tags 'tag4', 'tag3', 'tag2', 'tag1'

所以当我在寻找article4的标签时,应该这样排序:

1. tag4 (4 occurrences)
2. tag3 (3 occurrences)
3. tag2 (2 occurrences)
4. tag1 (1 occurrence)

这可以通过一个 MySql 查询实现吗? 目前我只是检索那篇文章的所有标签,然后是另一个数组,其中包含按出现次数排序的标签列表,然后只是使用后者手动对前一个数组进行排序。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    在这种情况下,我更喜欢使用LEFT JOIN,因为可能有一个标签未使用

    SELECT  a.tag_name
    FROM    tags a
            LEFT JOIN article_tags b
                ON a.tag_id = b.tag_id
    GROUP   BY a.tag_name
    ORDER   BY COUNT(b.tag_id) DESC
    

    如需进一步了解联接,请访问以下链接:

    【讨论】:

    • 感谢您的回复,但在我的情况下,其他查询似乎工作得很好。也感谢您的链接,它帮助我进一步了解了 JOIN :)
    【解决方案2】:

    我认为是

    SELECT t.tag_name, COUNT(at.*) as total
      FROM tags t
      JOIN article_tags at ON at.tag_id=t.tag_id
     WHERE t.tag_id IN (SELECT tag_id FROM article_tags at2 WHERE at2.article_id = ?)
     GROUP BY t.tag_name
     ORDER BY total DESC
    

    更新: 在 where 子句中添加文章 ID

    【讨论】:

      【解决方案3】:

      下面的 sql 语句应该会给你想要的结果。 将 777 替换为特定的文章 id

      select t.tag_name, count(at.article_tag_id) as [cnt]
      from article_tags at
      join tags t on (t.tag_id = at.tag_id)
      join articles a on (a.article_id = at.article_id)
      where a.article_id = 777
      group by tag_name
      order by cnt desc
      

      【讨论】:

      • 非常感谢您的回复
      猜你喜欢
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2014-10-21
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多