一个表tb:id int,tid int,tidp int,cid int,cidp int
id上建聚集索引
数据库里保存50万数据:tid>0,tidp>0,cid>0,cidp>0
有这样的查询
--...tid,tidp,cid,cidp任意组合
select id from tb where tid=2 and cidp=3;
select id from tb where tid=2 and cid=4;
select id from tb where tidp=1;
select id from tb where cidp=3;
建立复合索引tid asc,tidp asc,cid asc,cidp asc
我想写这样的查询 select id from tb where tid=1 and cid=2 and tidp>0
这里【特意加的tidp>0】是为了想让利用上索引上的cid可行吗?
如果不能利用上cid 这样的索引要怎么样建呢?
复合索引;建索引;sql?server
------解决方案--------------------
你这组合太多建议多建几个索引 不要搞一个复合四个字段的
tid如果出现很多 下面的就可以
on tb(tid) include(tidp ,cid ,cidp)
索引并没有太多的规则限制,一个表上几十个索引很正常的。
多建立一些也没事
可以用 sys.dm_db_missing_index_details 查看缺失的索引
------解决方案--------------------
http://www.cnblogs.com/worfdream/articles/2840582.html.
语句运行一段时间,mssql会给你建立索引的建议。如果连接所示。
可创建缺失索引,可删除运用少的索引。以及对索引的维护
------解决方案--------------------
一般不建议使用强制索引选项
索引要建立,就要有清理,可以通过
sys.dm_db_index_usage_stats
这个dmv去删除一些很少使用或者没被使用过的索引。
------解决方案--------------------
--还有查询是现在用了好多with(index(索引名))
也许可以把这部分索引提示去掉,让sql server自己去选择,再利用profiler/dmv去看看最慢的查询是什么,
适当的建几个索引还是不错的,
定期做老数据的归档。
------解决方案--------------------
创建了索引,还要保证索引的统计信息是最新的。
根据你的查询语句,你可以给这4个字段分别建立索引,MSSQL的优化器会根据where后面出现的多个字段,选择使用索引交叉技术来创建覆盖索引,或者使用索引连接。