zoukankan      html  css  js  c++  java
  • SQL Join 与 In的效率

    今天在优化朋友的一个系统, 主要他们前期是叫人外包写的, 越来越慢, 导出订单明细时, 基本都是TimeOut, 我查看到这里面是这样写:

    select * from Orders where ID in (select OrderID from OrderDetail where ProductSKU='106961105540')  and  CreateTime>='2019-01-01 12:51' and CreateTime<='2019-01-24 12:51'

    括号里面OrderDetail查询到六千多条记录,

    Orders 表一共81万多个记录

    OrderDetail 表有180万多个记录

    我的天哪, 怎可能不会TimeOut呢, 查询都要几十秒才执行出来结果。

    最后使用Join来帮他修改一下,SQL改成这样

    select * from (select * from Orders where Flag>0 and createtime>='2019-01-01 12:51' and createtime<='2019-01-24 12:51') as T1
    inner join (select distinct(OrderID) from OrderDetail where  ProductSKU='106961105540') as T2 on T1.ID=T2.OrderID

    这样执行, 只需要1秒左右就能执行出结果。

    所以建立, 在In与Join中, 千万要用Join, 除非数据量好少, 每个表记录少于千以下, 不然千万不要做这种In的蠢事。

  • 相关阅读:
    python列表切片
    python注释行与段落
    PCL安装与配置
    自动驾驶相关
    (转)ping命令
    (转)linux应用之test命令详细解析
    (转)shell解析命令行的过程以及eval命令
    (转)ssh-keygen 中文手册
    (转)stty 命令说明及使用讲解
    (转)CentOS下的trap命令
  • 原文地址:https://www.cnblogs.com/whtydn/p/10314135.html
Copyright © 2011-2022 走看看