我正在尝试做一个'类似帖子'的mysql字符串,我的所有帖子都有标签,所以我正在尝试这个查询:
SELECT articles.id,title,cover_image
FROM articles
INNER JOIN article_tags ON (article_tags.article_id = articles.id)
WHERE article_tags.tag_id
IN (312,13016,109,120,1493,103,1667,13015,331,5,564,13014,1670,113,13045)
AND articles.id <> 88230
它以某种方式完成工作,但问题是这些帖子与原帖不太相关, 例如,如果一个标签是'酷',那么我会得到标签酷的任何帖子
理想情况下,我想要的是根据标记出现的次数对这些结果进行排序, 例如:
article 1 has tags: tag1, tag2, tag3, tag4, tag5
article 2 has tags: tag2, tag3, tag4,
article 3 has tags: tag1, tag4
article 4 has tags: tag1, tag2, tag4, tag5
所以我希望sql返回这组结果:
tag1,tag4,tag2,tag3
答案 0 :(得分:2)
你走在正确的轨道上。只需使用group by
查找匹配数量并按顺序排序:
SELECT articles.id, title, cover_image
FROM articles INNER JOIN
article_tags
ON article_tags.article_id = articles.id
WHERE article_tags.tag_id IN (312,13016,109,120,1493,103,1667,13015,331,5,564,13014,1670,113,13045) AND
articles.id <> 88230
GROUP BY articles.id,title, cover_image
ORDER BY count(*) DESC;
您也可以在count(*) as NumMatches
中添加select
。