zoukankan      html  css  js  c++  java
  • 数据库的优化(非连接查询和连接查询的巧用)

    对于同一个问题, 在数据库查询的时间有很多方法,都能实现自己想要的结果,但是速度有快又慢,这就涉及到数据库的优化问题,虽然小生不才,真正刚刚接触数据库不久,但是遇到一个问题,感觉属于一个常见问题。情况是这样的

    在张总表(T_Product_Sale商品的总的生产和销售表)里面,还有二关联的表(一个是代理商退货表T_Oda,还有个是售后维修表T_Repair。),现在要根据这三个表要导出另外一个表(T_Return)

    当我想算出本月的销售量的时候问题就出现了,

    一种方法是要可以根据T_return的参数(月份,商品型号)来给T_Product_Sale表来进行连接查询。

     select replace (convert(char(7),B.scan_date),'/','') as MonthType
        ,count(*) as AmountSale
        ,GdsName as GdsName
       into #AmtSaleTemp
       from T_Return A
         ,T_Product_Sale B
      where A.MonthType = replace (convert(char(7),B.scan_date),'/','')
      group by replace (convert(char(7),B.scan_date),'/',''),GdsName

    另外一个方法是通过T_Product_Sale自身查询。

    sql如下:

      select dbo.F_Tanc_MonthType(scan_date) as MonthType
              ,GdsName = ( case
           when item_name like '%IdeaPadU%' then 'U1Pad'
           else 'Y1011' end)
              ,count(*) as AmountSale
         into #AmtSaleTemp
         from T_Product_Sale 
        group by dbo.F_Tanc_MonthType(scan_date)
       ,( case
        when item_name like '%IdeaPadU%' then 'U1Pad'
        else 'Y1011' end)

    第一种方法实现的时间是一1分钟30多秒,第二种方法用了五秒,而且第二种方法还把所有行数出来了,第一个只把T_Return要求的行数查询出来了

    反思一下这样的情况,其实是考虑问题的角度不一样,一种是很直接的的连接查询(按条件根据要求去查询),另一个是从全局来看非连接查询就搞定了

    最终都是通过#AmtSale这个临时表

     update A
      set A.AmountFr=B.AmountFr
        from T_Return A
       ,#AmtSale B
       where A.MonthType=B.MonthType
      and A.GdsName = B.GdsName
    来把数据更新到表T_Return里面

  • 相关阅读:
    python,selenium遇到的问题
    python环境配置
    性能测试函数
    性能测试的关注点
    环境配置
    性能监控工具使用
    linux路径
    linux权限
    自动化测试工具
    书籍
  • 原文地址:https://www.cnblogs.com/lzhp/p/2680816.html
Copyright © 2011-2022 走看看