我的对象模型如下所示,希望您输入要创建的索引数量,以加快查询响应(在 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且年份=2010的用户中选择*;
- 从组织 = 1、年份 = 2010 且 isSytem = true 或 false 的用户中选择 *; (即系统用户或应用程序定义的用户)
- 从组织 = 1、年份 = 2010、isSytem = false 且 userType = 经理的用户中选择 *(即所有经理)
- 从组织 = 1、年份 = 2010、isSytem = false 且 userType = Employee 的用户中选择 *(即所有员工)
- 从组织 = 1、年份 = 2010、isSytem = false、userType = Manager、status = ACTIVE 的用户中选择 *(即活跃用户)
从组织=1、年份=2010、createdBy='Sam' 或 'Joe' 的用户中选择 * [6] 是否需要一个不同的多列索引,由上述 3 列组成?
由于我们按照最初的假设创建多列索引,因此我可以安全地删除模型中当前定义的各个索引(idx_user_org_id、idx_user_year_id、idx_user_created_by)吗?
最佳答案
您应该切换索引中列的顺序:
(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
Does [6] need a different multi column index, consisting of the above 3 columns?
它不需要需要新索引 - 它可以使用现有索引,但效率较低 - 仅使用前两列。不过,为此查询添加新索引看起来是个好主意。
can I safely remove the individual indexes
是的。您应该删除未使用的索引,否则它们只会占用磁盘空间并减慢表修改速度,而不会带来任何好处。
关于mysql - 为了更快的查询应该创建多少索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3749749/