今天在优化朋友的一个系统, 主要他们前期是叫人外包写的, 愈来愈慢, 导出订单明细时, 基本都是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'select
括号里面OrderDetail查询到六千多条记录,im
Orders 表一共81万多个记录数据
OrderDetail 表有180万多个记录查询
个人天哪, 怎可能不会TimeOut呢, 查询都要几十秒才执行出来结果。di
最后使用Join来帮他修改一下,SQL改为这样join
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.OrderIDtime
这样执行, 只须要1秒左右就能执行出结果。系统
因此创建, 在In与Join中, 千万要用Join, 除非数据量好少, 每一个表记录少于千如下, 否则千万不要作这种In的蠢事。