我正在使用此查询在表内搜索:
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
是否还有优化此查询的方法?更好的写法?
最佳答案
-
is this the right sintax?
是的。如
SELECT
Syntax 下所述:A
select_expr
can be given an alias usingAS <em>alias_name</em>
. The alias is used as the expression's column name and can be used inGROUP BY
,ORDER BY
, orHAVING
clauses. -
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 extraORDER BY
columns are constants in theWHERE
clause.但是,可以:
使用
WHERE
过滤结果集,仅显示感兴趣的记录子句,从而减少必须排序的结果数量;和/或通过从
ORDER BY
中删除不需要的列来减少每个排序步骤需要执行的最大比较次数条款。
关于mysql - SQL查询匹配别名和排序依据并优化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422134/