zoukankan      html  css  js  c++  java
  • 遇到索引的那点事

    1.两表连查  共同点 都有id  一个id是int类型 一个id是nvarchar   

    select a.name,sum(b.chengji) from  a,b where a.id=b.id and a.name not in ('0',null)

    耗时:32秒

    经过csdn大神指点之后

    改善:

    select a.name,sum(b.chengji) from  a,b where a.id=b.id and a.name <>'0' and a.name is not null

    耗时:32秒

    发现还是那么慢

    后来百度 google    研究表结构 发现 两表中的id类型不同   突然脑海浮现 id和字符类型 速度慢 

    id  nvarchar-->  id int 

    然后子啊

    select a.name,sum(b.chengji) from  a,b where a.id=b.id and a.name <>'0' and a.name is not null

    耗时:200毫秒

    ////////////////

    1.转换字符的函数:cast(id as int ) 优先于 convert(int ,id) 

    2.尽量不要用 not in

    3.如果列很多 那么使用 no texists

    4.在两张表比较 的那列数据加上聚集索引更快(请问下 聚集索引 是不是等于 群集索引呢?)

    5.注意细节

    ----------------可爱的分割线--------------

    关于组合索引

    我有一张视图 大概就是这样

     select a.name,a.sex,a.address,sum(b.qw1),sum(b.qw2),sum(c.qw3),sum(d.qw4) from a,b,c,d where a.id=b.id and a.id=c.id and a.id=d.id group by a.name,a.sex,a.address

    这里应该使用组合索引 

    因为name最常用 sex次之,address再次之

    所以建立组合索引应该这样: 加上复合索引,并各自再设置一个独立索引 

    create   index   IX_name_sex_address_表   on   表(name,sex,address) 
    create   index   IX_name_表   on   表(name) 
    create   index   IX_sex_表   on   表(sex) 
    create   index   IX_address_表   on   表(address) 

    参考:http://topic.csdn.net/t/20040330/13/2903545.html

    提到in用exists或者这样

    select * from spt_values where number in (1,2,4)
    
    select spt.* from spt_values as spt join(
    	select number=1
    	union all select number=2
    	union all select number=4
    )b on spt.number=b.number
    
    --可以这样简写
    --select spt.* from spt_values as spt join(
    --	select number=1
    --	union all select 2
    --	union all select 4
    --)b on spt.number=b.number
    

  • 相关阅读:
    Map容器家族(LinkedHashMap源码详解)
    树篇3-平衡二叉查找树之红黑树
    树篇2-平衡二叉查找树之AVL树
    树篇1-二叉查找树
    Map容器家族(HashMap源码详解)
    位运算符的基本使用和注意事项
    android中获取屏幕的信息
    获取activity的根视图
    初来咋到,请多指教
    linux死机解决办法
  • 原文地址:https://www.cnblogs.com/0banana0/p/2086393.html
Copyright © 2011-2022 走看看