這兩個表包含超過1m個記錄。使用「或」時優化MySQL查詢
該查詢需要15秒的運行,返回1條記錄(正確):
select orders.*
from orders
left join orders_details on orders.orderID=orders_details.orderID
where
orders_details.trackingRef='GYD41624'
or orders.orderID = (
select distinct orderID from orders_rebookings
where trackingRef='GYD41624'
)
group by orders.orderID
而如果我與每個where條件運行查詢分開,然後各自非常快:
這需要0.0015秒(1個找到匹配):
select orders.*
from orders
left join orders_details on orders.orderID=orders_details.orderID
where orders.orderID = (select distinct orderID from orders_rebookings where trackingRef='GYD41624')
group by orders.orderID
而這幾乎不需要花時間,沒有發現匹配(這是正確的):
select orders.*
from orders
left join orders_details on orders.orderID=orders_details.orderID
where orders_details.trackingRef='GYD41624'
group by orders.orderID
所以,如果我有兩個非常快的查詢,我怎麼能使第一個包含「或」幾乎一樣快?
- 將子查詢中的區別替換爲一個組 –