今天在優化朋友的一個系統, 主要他們前期是叫人外包寫的, 愈來愈慢, 導出訂單明細時, 基本都是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的蠢事。