为什么排序时不使用索引?

发布于 2024-11-07 18:29:21 字数 557 浏览 0 评论 0原文

我有这个表结构:

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)
)

使用这个索引:

CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);

login_count列可能由NULL值组成,我需要选择按login_count降序排列的所有用户,并且需要NULL位于末尾。

不幸的是这个查询:

SELECT * FROM users ORDER BY login_count DESC LIMIT 30;

不会使用索引,所以空值在开始,为什么?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初相遇 2024-11-14 18:29:21

索引的定义方式不会改变查询的含义。为了使用索引,索引的顺序必须与查询的顺序相匹配。

话虽如此,MySQL 似乎不支持 nulls last。尝试:

SELECT  * 
FROM    users
ORDER BY
        case when login_count is null then -1 else login_count end DESC 
LIMIT 30;

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. Try:

SELECT  * 
FROM    users
ORDER BY
        case when login_count is null then -1 else login_count end DESC 
LIMIT 30;
一抹苦笑 2024-11-14 18:29:21

您的查询实际上是ORDER BY login_count DESCNULLS FIRSTLIMIT 30,如下所述此处。在此页面上,它描述了索引如何满足排序:

按升序存储的索引
首先带有空值可以满足
ORDER BY x ASC NULLS FIRSTORDER BY x DESC NULLS LAST
取决于扫描的方向。

所以你的索引是相同的 - 它可以满足 ASC NULLS FIRSTDESC NULLS LAST,但你的查询是 DESC NULLS首先

Your query is effectively ORDER BY login_count DESCNULLS FIRSTLIMIT 30 as explained here. 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 or ORDER BY x DESC NULLS LAST
depending on which direction it is scanned in.

So your index is the same - it can satisfy ASC NULLS FIRST and DESC NULLS LAST, but your query is DESC NULLS FIRST.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文