首页 > 解决方案 > 我应该在多列索引中创建布尔字段索引吗?

问题描述

例如,我想通过publish_dateand检索下一个/上一个帖子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

哪个索引会更好?

或者

标签: mysqldatabasepostgresqlindexing

解决方案


让我首先重写查询,使其更有意义:

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

当它是复合索引的一部分时,每列的基数无关紧要。


推荐阅读