zoukankan      html  css  js  c++  java
  • sql相关优化

    一、笛卡尔积介绍

    1. 笛卡尔积全称笛卡尔乘积,笛卡尔乘积是指在数学中,两个集合XY的笛卡尔积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员

    2. 表达式为:A×B = {(x,y)|x∈A∧y∈B}

    3. 笛卡尔积在SQL中的应用,常用表达式为:

      select * from 【表名,别名】,【表明,别名】 where 【别名.关联字段名=别名.关联字段名】

      case: select * from depart a,Person b where a.Id=b.departId

    4. 具体示例如下:我新建了一个部门和一个人员表

    5. 相关笛卡尔积的查询表达式以及相关运行结果如下:

     6. 注意事项:运用笛卡尔积表示式,其实就是类似于内连接查询,只不过不同的是,内连接查询会进行全表连接查询,而笛卡尔积查询首先运行的是后方的where条件进行过滤一遍,然后再进行乘积。这样可以更加有效的提高sql的查询效率,同时,如果需要进行左或者右连接查询时,就不能使用笛卡尔积查询,不然会导致最终的结果不正确。

    二、sql进行优化

     1. sql的查询步骤: 先进行where条件的过滤,然后再进行select 字段的查询。所以sql 的优化应该首先放置在where条件的应用上。

     2. 应该避免在where条件中对null值进行判断,否则会导致进行全表查询。如:

      select id from where number is null

      应该给number赋初始值为0,然后修改为

      select id from where number=0

    3. in 和 not in 也要慎用,否则会导致全表扫描,如:

      select id from t where num in(1,2,3)    
      对于连续的数值,能用 between 就不要用 in 了:    
      select id from t where num between 1 and 3

    4. 应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如:    
      select id from t where number/2=100    
      应改为:    
      select id from t where number=100*2  

    5. 任何地方都不要使用 select * from t ,用具体的字段列表代替“*”

    6. 用 exists 代替 in

      select num from a where num in(select num from b)    
      用下面的语句替换:    
      select num from a where exists(select 1 from b where num=a.num)

    7.尽量使用inner join 查询,并且可以用笛卡尔积表达式进行替代。

  • 相关阅读:
    安全编码1
    VPP tips
    VPP概述汇总
    C语言安全编码摘录
    TCP-proxy
    Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.4. Matplotlib: plotting
    Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.3. NumPy: creating and manipulating numerical data
    Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.2. The Python language
    Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.1. Python scientific computing ecosystem
    25马5跑道,求最快的五匹马的需要比赛的次数
  • 原文地址:https://www.cnblogs.com/wangjinya/p/12110147.html
Copyright © 2011-2022 走看看