【问题标题】:How to set priority for columns and sort the results by that priority?如何设置列的优先级并按该优先级对结果进行排序?
【发布时间】:2015-10-15 20:00:47
【问题描述】:

我有一张这样的桌子:

// mytable
+----+---------+-------------------------------+
| id |   title |           content             |
+----+---------+-------------------------------+
| 1  |  hello  |  how are you?                 |
| 2  |  you    |  it is  content2              |
| 3  |  what   |  hello is a word for greating |
| 4  |  mouse  |  it is content4               |
+----+---------+-------------------------------+

嗯,我想给titlecontent 更优先。我的意思是,我想显示来自title 列的所有结果(第一个),然后显示来自content 列的所有结果(第二个)。这也是我的查询:

select * from mytable where match(title, content) against($word);

这里还有两个例子:

示例 1:

$word = 'you';

我想要这个输出:(专注于排序)

+----+---------+-------------------------------+
| id |   title |           content             |
+----+---------+-------------------------------+
| 2  |  you    |  it is  content2              |
| 1  |  hello  |  how are you?                 |
+----+---------+-------------------------------+

示例 2:

$word = 'hello';

我想要这个输出:(专注于排序)

+----+---------+-------------------------------+
| id |   title |           content             |
+----+---------+-------------------------------+
| 1  |  hello  |  how are you?                 |
| 3  |  what   |  hello is a word for greating |
+----+---------+-------------------------------+

我再次强调,我想要所有来自title 列的结果,然后所有来自content 列的结果。有什么解决办法吗?

【问题讨论】:

  • 为什么不按特定值在一个选择中按列排序?

标签: mysql sorting full-text-search sql-order-by


【解决方案1】:

您需要做的就是使用 CASE 和单词匹配的条件顺序。这是一个让你开始的例子

SELECT title, content
FROM tablename
ORDER BY CASE
    WHEN title LIKE '%you%' THEN 1
    WHEN content LIKE '%you%' THEN 2
    ELSE 3
END;

FIDDLE EXAMPLE

【讨论】:

    【解决方案2】:

    对 2 列运行 2 个单独的查询,并将它们与联合合并为单个结果集:

    select * from mytable where match(title) against($word);
    union distinct
    select * from mytable where match(content) against($word);
    

    编辑:

    如果你不喜欢联合的方式,那么就创建3个全文索引,一个在标题上,一个在内容上,一个在2的组合上。然后使用下面的方法:

    SELECT title, content,
      MATCH (title) AGAINST ($word) AS c1,
      MATCH (content) AGAINST ($word) AS c2
    FROM tablename
    WHERE MATCH (title,content) AGAINST ($word)
    ORDER BY IF(c1> 0,1,0)
    

    组合索引将用于搜索,而单个索引将用于产生权重。但是,如果一个词被发现的次数太多,它的权重可能会降低到 0。

    【讨论】:

    • 是的,看起来是对的,但实际上并没有优化。使用两个分隔的select 子句仅用于排序 ...在我看来不值得。
    【解决方案3】:

    好像你快到了。怎么样:

    select * from mytable where match(title) against($word);
    union
    select * from mytable where match(content) against($word);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多