mysql - SQL查询匹配别名和排序依据并优化查询

标签 mysql sql sql-order-by query-optimization match

我正在使用此查询在表内搜索:

SELECT 
   *,
   MATCH(tags,title,description) 
      AGAINST ('hey you are you in' IN BOOLEAN MODE) AS score 
FROM table  
ORDER BY insert_datetime DESC, id DESC 

我需要的是使用别名“score”来排序结果,这是正确的语法吗?:

SELECT 
   *,
   MATCH(tags,title,description) 
     AGAINST ('hey you are you in' IN BOOLEAN MODE) AS score 
FROM table  
ORDER BY score DESC, insert_datetime DESC, id DESC 

是否还有优化此查询的方法?更好的写法?

最佳答案

  1. is this the right sintax?

    是的。如 SELECT Syntax 下所述:

    A select_expr can be given an alias using AS <em>alias_name</em>. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses.

  2. is also there anyway to optimize this query ? better way to write that?

    如果您不需要结果集中的相关性得分,则无需选择它:

    SELECT   *
    FROM     table  
    ORDER BY MATCH(tags, title, description) AGAINST (
               'hey you are you in' IN BOOLEAN MODE
             ) DESC, insert_datetime DESC, id DESC
    

    但遗憾的是,正如 ORDER BY Optimization 所建议的那样, MySQL 无法避免在按 MATCH() ... AGAINST() 等函数的结果排序时进行文件排序。 :

    In some cases, MySQL can use an index to satisfy an ORDER BY clause without doing any extra sorting.

    The index can also be used even if the ORDER BY does not match the index exactly, as long as all of the unused portions of the index and all the extra ORDER BY columns are constants in the WHERE clause.

    但是,可以:

    • 使用 WHERE 过滤结果集,仅显示感兴趣的记录子句,从而减少必须排序的结果数量;和/或

    • 通过从 ORDER BY 中删除不需要的列来减少每个排序步骤需要执行的最大比较次数条款。

关于mysql - SQL查询匹配别名和排序依据并优化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422134/

相关文章:

Mysql 事件提要设计

python - 如何更新表格所有行中的列?

sql - 自定义 SQL Order By 语句

sql - 在 SQL Server 中计算 XML 中的非空节点数

mysql 统计一个值显示多列

mysql - 如何将我计算机上的 React 应用程序连接到 godaddy 上的 mysql 数据库

mysql - 如何选择外键选项以获得更好的数据库

node.js - rethinkdb orderby 不区分大小写

linq - 通过MvvmCross在SQLite插件上使用多个字段的linq查询“orderby”不起作用

mysql - 动态选择字段以从中选择数据