【问题标题】:How can I modify this query to order by matches?如何修改此查询以按匹配排序?
【发布时间】:2014-09-30 02:26:19
【问题描述】:

此查询根据文章表中的行是否具有与给定关键字列表匹配的标签来获取行。我想按与搜索匹配的标签数量对结果进行排序。我该怎么做?

SELECT DISTINCT a.*, 
FROM   `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE  t.keyword IN ("apples", "bananas", "oranges")

|--- Article Tags ---|
|--article_tag_id----|
|--article_id--------|
|-------tag_id-------|
|--------------------|

|-------Tags---------|
|------tag_id--------|
|------keyword-------|
|--------------------|

【问题讨论】:

  • 你是什么意思:找到的不同关键字的数量或这些关键字的出现次数?具有所需结果的简单示例表会很有帮助。
  • 说有两篇文章:第一篇有苹果和香蕉的标签。第二个有苹果和橙子的标签。假设用户使用“applesbananaskiwi”字符串进行搜索。第一篇文章会首先出现,因为它匹配两个标签(苹果和香蕉),而第二篇文章会出现第二个,因为它只匹配一个标签(苹果)。上面的查询可以做到这一点吗?

标签: mysql search tags keyword


【解决方案1】:

你可以在一行中使用一些东西

SELECT a.*, COUNT(t.keyword) as matches
FROM   `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE  t.keyword IN ("apples", "bananas", "oranges")
GROUP BY a.article_id
ORDER BY COUNT(t.keyword) DESC;

如果您只想要不同的关键字,请使用

SELECT a.*, COUNT(DISTINCT t.keyword) as matches
FROM   `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE  t.keyword IN ("apples", "bananas", "oranges")
GROUP BY a.article_id
ORDER BY COUNT(DISTINCT t.keyword) DESC;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多