zoukankan      html  css  js  c++  java
  • 如何让你的SQL运行得更快

    一、不合理的索引设计----
    例:表record620000行,看在不同的索引下,下面几个 SQL的运行情况:
    ---- 1.date上建有一非个群集索引
    select count(*) from record where date >'19991201' and date < '19991214'and amount >2000 (25)
    select date ,sum(amount) from record group by date(55)
    select count(*) from record where date >'19990901' and place in ('BJ','SH') (27)
    ---- 分析:----
    date上有大量的重复值,在非群集索引下,数据在物理上随机存放在数据上,在范围查,必须执行一次表描才能找到一范内的全部行。
    ---- 2.date上的一个群集索引
    select count(*) from record where date >'19991201' and date < '19991214' and amount >2000 14秒)
    select date,sum(amount) from record group by date28秒)
    select count(*) from record where date >'19990901' and place in ('BJ','SH')14秒)
    ---- 分析:---- 在群集索引下,数据在物理上按序在数据上,重复值也排列在一起,因而在范围查,可以先找到个范的起末点,且只在个范描数据,避免了大范围扫描,提高了查询速度。
    ---- 3.placedateamount上的合索引
    select count(*) from record where date >'19991201' and date < '19991214' and amount >2000 26秒)
    select date,sum(amount) from record group by date27秒)
    select count(*) from record where date >'19990901' and place in ('BJ, 'SH')< 1秒)
    ---- 分析:---- 是一个不很合理的合索引,因它的前列是place,第一和第二条SQL没有引用place,因此也没有利用上索引;第三个SQL使用了place,且引用的所有列都包含在合索引中,形成了索引覆盖,所以它的速度是非常快的。
    ---- 4.dateplaceamount上的合索引
    select count(*) from record where date >'19991201' and date < '19991214' and amount >2000(< 1)
    select date,sum(amount) from record group by date11秒)
    select count(*) from record where date >'19990901' and place in ('BJ','SH')< 1秒)
    ---- 分析:---- 是一个合理的合索引。它将date列,使SQL都可以利用索引,并且在第一和第三个SQL中形成了索引覆盖,因而性能达到了最
    ---- 5.总结----
    缺省情况下建立的索引是非群集索引,但有它并不是最佳的;合理的索引设计要建立在种查询的分析和预测上。
    一般来
    .有大量重复值、且常有范围查询between, >,< >=,< =)和order bygroup by生的列,可考建立群集索引;
    .常同存取多列,且列都含有重复值可考建立合索引;
    .合索引要尽量使关键查询形成索引覆盖,其前列一定是使用最繁的列。
    二、不充份的接条件:
    例:表card7896行,在card_no上有一个非聚集索引,表account191122行,在account_no上有一个非聚集索引,看在不同的表接条件下,两个SQL行情况:
    select sum(a.amount) from account a,card b where a.card_no = b.card_no20秒)
    select sum(a.amount) from account a,card b where a.card_no = b.card_no and a.account_no=b.account_no< 1秒)
    ---- 分析:---- 在第一个接条件下,最佳查询方案是将account作外表,card作内表,利用card上的索引,其I/O次数可由以下公式估算
    account上的22541+(外account191122*card对应表第一行所要找的3=595907I/O
    在第二个接条件下,最佳查询方案是将card作外表,account作内表,利用account上的索引,其I/O次数可由以下公式估算:外card上的1944+(外card7896*account对应一行所要找的4= 33528I/O
    ,只有充份的接条件,真正的最佳方案才会被行。
    总结
    1.多表操作在被实际执行前,查询优化器会根据接条件,列出几可能的接方案并从中找出系统开销最小的最佳方案。接条件要充份考虑带有索引的表、行数多的表;内外表的选择可由公式:外表中的匹配行数*表中一次找的次数确定,乘最小最佳方案。
    2.行方案的方法-- set showplanon,打showplan选项,就可以看到序、使用何索引的信息;想看更详细的信息,需用sa角色dbcc(3604,310,302)
  • 相关阅读:
    Python xlrd.biffh.XLRDError: Excel xlsx file; not supported
    Python 报/usr/bin/python^M: bad interpreter: No such file or directory
    Linux curl命令
    课程学习总结报告
    信息安全实验二
    结合中断上下文切换和进程上下文切换分析linux内核的一般执行过程
    深入理解Linux系统调用
    基于mykernel2.0编写一个操作系统内核
    如何评测软件工程知识技能水平
    创新产品的需求分析:未来图书会是什么样子?
  • 原文地址:https://www.cnblogs.com/ivanyb/p/1070978.html
Copyright © 2011-2022 走看看