我不确定这个问题是否在本网站的其他地方得到了回答,但是我很难用语言来解释我的问题。
这里是:
我想做的是通过用户选择的标签对crawler_results中的文章进行排序。因此,标签在文章中出现的次数越多(count_tags越大),层次结构中的标记就越高。

我有4个表:rawler_results(用于存储文章的位置),标签(用于存储标签名称的位置),article_tags(用于存储标签的ID和标签的出现次数)和user_tags(用于存储用户的id和tag_id的位置)。

我尝试过:

      SELECT cr.id, title, count_tags, t.tag
      FROM crawler_results cr
      INNER JOIN article_tags at
      ON cr.id = at.article_id
      INNER JOIN tags t
      ON t.id = at.tag_id
      INNER JOIN user_tags ut
      ON ut.tag_id = at.tag_id
      AND user_id = '$user_id'
      ORDER BY count_tags DESC


该查询显示按count_tags排序的文章,但不幸的是,它对文章包含的所有标签都这样做。例如,如果有这样的文章:“ Stackoverflow溢出真棒!”并且用户选择了“堆栈”和“溢出”作为标签,“溢出”应该是查询所看到的唯一标签,因为它看起来比“堆栈”要多。

我觉得这与GROUP BY有关-对吗?我只是不知道它是如何工作的。

提前致谢!
如果您需要更多信息,请告诉我。

编辑:
这是我的桌子:

crawler_results:

       | id         | title       | content      |
       |:-----------|------------:|:------------:|
       | 1          | Some title  | Some content |
       | 2          | Other title | Other content|


标签:

       | id         | tag         |
       |:-----------|------------:|
       | 1          | Some tag    |
       | 2          | Other tag   |


article_tags:

       | id         | tag_id      | article_id   | count_tags   |
       |:-----------|------------:|:------------:|:------------:|
       | 1          | 1           | 1            | 5            |
       | 2          | 2           | 2            | 10           |
       | 3          | 1           | 2            | 8            |


user_tags:

       | id         | user_id     | tag_id       |
       |:-----------|------------:|:------------:|
       | 1          | 1           | 1            |
       | 2          | 1           | 2            |

最佳答案

这是似乎返回预期结果的查询:

SELECT cr.id
    , cr.title
    , SUM(CASE
           WHEN ut.tag_id IS NOT NULL THEN at.count_tags
           ELSE 0
          END) AS matching_tags
FROM crawler_results cr
INNER JOIN article_tags at ON cr.id = at.article_id
LEFT JOIN user_tags ut ON ut.tag_id = at.tag_id
                         AND user_id = '$user_id'
GROUP BY cr.id, cr.title
ORDER BY matching_tags DESC


我只是添加了一个GROUP BY子句,以便计算每篇文章的标签数量,然后对结果进行降序排序。

希望这会有所帮助。

关于mysql - mysql按标 checkout 现顺序排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26287333/

10-14 11:27
查看更多