mysql - 我应该在多列索引中创建布尔字段索引吗?
问题描述
例如,我想通过publish_date
and检索下一个/上一个帖子published=True
。我应该创建一个索引publish_date, published
还是只创建一个publish_date
?
表是
id (int)
title (char)
description (text)
publish_date (datetime)
published (bool)
查询是:
select *
from table
where publish_date > current_post.publish_date
and published = True
order by publish_date
limit 1
哪个索引会更好?
- 多列索引
(publish_time, published)
或者
- 单列索引仅
(publish_time)
解决方案
让我首先重写查询,使其更有意义:
select * from table
where publish_date >= '2020-01-01'
and published = True
ORDER BY publish_date
LIMIT 1
该索引将是最佳的:
INDEX(published, publish_date)
按该顺序排列列。首先是用 测试的东西=
,然后最多是一个范围。这两列都将在WHERE
. WHERE
而且,由于它处理整个ORDER BY
. ORDER BY
匹配得很好WHERE
,它会帮助它,从而避免任何类型。
更多讨论:http: //mysql.rjweb.org/doc.php/index_cookbook_mysql
也可以看看EXPLAIN SELECT ...
当它是复合索引的一部分时,每列的基数无关紧要。
推荐阅读
- html - 为什么 background-image:url 不能与本地 jpeg 一起使用?但它与远程 pexels jpeg...?
- signalr - 将标头添加到 @aspnet/signalr Javascript 客户端
- node.js - Gulp 4 无法完成 sass 任务
- java - 当 Java 中的线程死亡时,ThreadPoolExecutor 会发生什么
- amazon-ec2 - 我无法访问亚马逊 ec2(ubuntu) 服务器
- java - 如何创建一个在最后一个订阅者取消订阅后立即完成的 Flowable
- node.js - 手动结束时如何优雅地退出 Node 程序(Ctrl+C、kill 命令等)?
- python - 在熊猫中使日期不那么具体
- gdb - 用 riscV-gdb 连接到自制的 openOCD
- java - Java 8 将员工名字从 Robert 更改为 Ronald 并返回原始列表