应该为更快的查询创建多少个索引

时间:2010-09-20 08:29:21

标签: mysql database jpa indexing

我的对象模型如下所示,并希望您输入索引的数量以便更快地查询响应(在h2,mysql上)。假设和问题在以下模型下面给出。

@Entity
@Table(name = "user")
public class User  {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false, insertable = false, updatable = false)
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @ForeignKey(name = "fk_user_org_id")
    @Index(name = "idx_user_org_id")
    @JoinColumn(name = "org_id", nullable = false, referencedColumnName = "id")
    @NotNull
    private Organization organization;

    @ManyToOne(fetch = FetchType.LAZY)
    @ForeignKey(name = "fk_user_year_id")
    @Index(name = "idx_user_year_id")
    @JoinColumn(name = "year", nullable = false, referencedColumnName = "id")
    @NotNull
    private Year year;

    @ManyToOne(fetch = FetchType.LAZY)
    @ForeignKey(name = "fk_user_created_by")
    @Index(name = "idx_user_created_by")
    @JoinColumn(name = "created_by", nullable = false, referencedColumnName = "id")
    @NotNull
    private User createdBy;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "desc")
    private String desc;

    @Column(name = "is_system", length = LEN_1)
    @Type(type = "org.hibernate.type.YesNoType")
    private boolean isSystem = false;

    @Column(name = "user_type", nullable = false)
    private UserType userType;

    @Column(name = "status", nullable = false)
    @NotNull
    private Status status;

}

我们的计划是使用多列索引而不是单列索引(即基于(organization,year,isSystem,status,userType,createdBy)创建索引user_idx)。假设我有这个索引,我是否会针对下面列出的查询获得优化的响应。

  1. select * from user where organization = 1 and year = 2010;
  2. select * from user where organization = 1 and year = 2010 and isSytem = true或false; (即系统用户或应用程序定义的用户)
  3. select * from user where organization = 1 and year = 2010 and isSytem = false and userType = Manager(即所有经理)
  4. select * from user where organization = 1 and year = 2010 and isSytem = false且userType = Employee(即所有员工)
  5. select * from user where organization = 1 and year = 2010 and isSytem = false且userType = Manager and status = ACTIVE(即活跃用户)
  6. 从用户中选择*,其中organization = 1和year = 2010并且createdBy ='Sam'或'Joe' [6]是否需要不同的多列索引,包括上述3列?

  7. 由于我们按照原始假设创建了一个多列索引,我是否可以安全地删除模型中当前定义的各个索引(idx_user_org_id,idx_user_year_id,idx_user_created_by)?

1 个答案:

答案 0 :(得分:2)

您应该切换索引中列的顺序:

(organization, year, isSystem, userType, status, createdBy)

这样可以更好地为这两个查询提供服务:

select * from user where organization=1 and year=2010 and isSystem=false and userType=Manager
select * from user where organization=1 and year=2010 and isSystem=false and userType=Employee
  

[6]是否需要一个不同的多列索引,由上述3列组成?

它不需要一个新索引 - 它可以使用现有索引,但效率较低 - 只会使用前两列。为此查询添加新索引看起来不错。

  

我可以安全地删除单个索引

是。您应该删除未使用的索引,否则它们将占用磁盘空间并减慢表修改速度而不会带来任何好处。