CTOCIO IT专家网

天极传媒 比特网 | 天极网 | IT专家网 | IT商网 | 52PK游戏网 | 手机天极 | IT分众 |
IT专家网搜索

数据库 | Oracle | DB2 | SQL Server | MySQL | 商业智能 | BI | DBA | Sybase| SQL Server 2008

您现在的位置: IT专家网 > 数据库子站 > 数据库技巧

避免在SQL Server表中产生冗余索引

作者: Echo,  出处:IT专家网, 责任编辑: 李书琴, 
2008-03-14 11:10
  

  【IT专家网独家】

  问题:

  我现在正在Sql Server数据库设计一个新建客户表的索引,有三个不同的查询搜索可以满足需要。一个查询是根据姓(lastname)进行搜索,第二个查询搜索是根据姓(lastname)和名(firstname)进行搜索,而第三个查询是根据姓(lastname)和一个激活的标识进行搜索。我应该怎么建立我的索引呢?

  专家解答:

  我曾经碰到过很多数据模型实例,原来的数据库开发员会用以下三种不同的索引来解决这个问题:

  create index ix_customer_lastname on dbo.Customer(lastname)
  GO
  create index ix_customer_lastname_firstname on dbo.Customer(lastname, firstname)
  GO
  create index ix_customer_lastname_activesw on dbo.Customer(lastname, activesw)
  GO

  但是事实是,在这种情况下,你只需要一种索引!

  下面的这些查询

  select * from dbo.Customer where lastname = 'Washington'
  GO
  select * from dbo.Customer where lastname = 'Washington' and activesw = 1
  GO
  select * from dbo.Customer where firstname = 'George' and lastname = 'Washington'
  GO
  select * from dbo.Customer
  where firstname = 'George' and lastname = 'Washington' and activesw = 1
  GO

  全都可以通过以下这个索引进行。

  create index ix_customer_lastname on dbo.Customer(lastname, firstname, activesw)
  GO

  每个索引需要的首要列是lastname,这是最重要的一个列。SQL Server根据每个索引的首要列以柱状图的方式来进行频数分布统计。它也会记录二级选择数据信息作为额外索引列置换。

  数据库里含有冗余索引会造成SQL Server系统资源浪费,因为这样数据库引擎就不得不维持更大的数据结构。我们可以假设向数据库添加一个新的客户信息记录。新插入的lastname在进行每个索引逻辑排序的时候都需要计算在内,要维护这些索引不得不生产许多不必要的数据。而且,冗余索引还会浪费磁盘空间。

  让我们新建一个客户表和几个索引来说明这个问题。用下面的脚本可以创建一个客户表以及10,000行客户信息。

共4页。 1 2 3 4 :

网友评论

笔名 
请您注意:遵守国家有关法律、法规,尊重网上道德,承担一切因您的行为而直接或间接引起的法律责任。    IT专家网友拥有管理笔名和留言的一切权利。
  • 周排行榜
  • 月排行榜

邮件订阅


    
天极服务 | 关于我们 | 网站律师 | 加入我们 | 联系我们 | 广告业务 | 友情链接 | 我要挑错
All Rights Reserved, Copyright 2004-2008, Ctocio.com.cn
渝ICP证B2-20030003号 如有意见请与我们联系 powered by 天极内容管理平台CMS4i