【问题标题】:Should I create a booleanfield index in a multi column indexing?我应该在多列索引中创建布尔字段索引吗?
【发布时间】:2020-07-29 22:19:55
【问题描述】:

例如,我想检索publish_datepublished=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) 上建立单列索引

【问题讨论】:

  • 如果你使用多列索引,你需要一个逗号,而不是“and”。多久发布一次是真的?如果几乎总是这样,那么没有多大意义。如果几乎从不,那么您可能需要过滤索引,而不是多列。
  • 80% 已发布=true
  • publish_date>current_post.publish_date -- 嗯?你为什么提到publish_date 两次? current_post 没有被提及。
  • 我将它与 Web 应用程序一起使用。只是想知道哪种索引更适合这种情况。 @rickJames

标签: mysql database postgresql indexing


【解决方案1】:

让我先重写查询,让它更有意义:

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 BYORDER BYWHERE 匹配得很好,可以帮助解决它,从而避免任何排序。

更多讨论:http://mysql.rjweb.org/doc.php/index_cookbook_mysql

另见EXPLAIN SELECT ...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 2010-12-23
    • 2020-10-06
    • 2011-08-24
    • 2014-08-21
    • 2017-08-15
    • 1970-01-01
    • 2022-09-30
    相关资源
    最近更新 更多