[英]Why index is not used when ordering?
I have this table structure: 我有这个表结构:
CREATE TABLE users
(
uid bigint NOT NULL,
first_name character varying,
last_name character varying,
email character varying,
login_count integer,
CONSTRAINT users_pkey PRIMARY KEY (uid)
)
with this index: 具有此索引:
CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);
The login_count column may consists of NULL values and i need to select all users ordered descending by login_count and need NULLs to be at the end. login_count列可能包含NULL值,我需要选择按login_count降序排列的所有用户,并且需要在末尾使用NULL。
Unfortunately this query: 不幸的是这个查询:
SELECT * FROM users ORDER BY login_count DESC LIMIT 30;
won't use the index, so NULLs are at the beggining, why? 不会使用索引,因此NULL开头,为什么?
How an index is defined does not change the meaning of a query. 如何定义索引不会更改查询的含义。 In order for the index to be used, the ordering of the index has to match the ordering of the query.
为了使用索引,索引的顺序必须与查询的顺序匹配。
Having said that, it doesn't appear that MySQL supports nulls last
. 话虽如此, MySQL似乎并没有支持
nulls last
。 Try: 尝试:
SELECT *
FROM users
ORDER BY
case when login_count is null then -1 else login_count end DESC
LIMIT 30;
Your query is effectively ORDER BY login_count DESC
NULLS FIRST
LIMIT 30
as explained here . 您的查询是有效
ORDER BY login_count DESC
NULLS FIRST
LIMIT 30
为解释在这里 。 On this page it describes how an index can satisfy an ordering: 在此页面上 ,描述了索引如何满足排序要求:
An index stored in ascending order with nulls first can satisfy either
ORDER BY x ASC NULLS FIRST
orORDER BY x DESC NULLS LAST
depending on which direction it is scanned in.根据索引的扫描方向,首先以空值升序存储的索引可以满足
ORDER BY x ASC NULLS FIRST
或ORDER BY x DESC NULLS LAST
。
So your index is the same - it can satisfy ASC NULLS FIRST
and DESC NULLS LAST
, but your query is DESC NULLS FIRST
. 因此,您的索引是相同的-它可以满足
ASC NULLS FIRST
和DESC NULLS LAST
,但是您的查询是DESC NULLS FIRST
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.