2012-11-28 111 views
1

我有以下查詢選擇notes表中輸入(例如:bob)不在orders表中的所有內容。MySQL查詢重新設計

SELECT * FROM `notes` WHERE notes.customer_email NOT IN 
(SELECT customers_email_address FROM orders) 
AND ((customer_phone LIKE '%bob%') 
OR (customer_name LIKE '%bob%') 
OR (customer_email LIKE '%bob%')) 
AND customers_id IS NULL 
GROUP BY `customer_email` 
ORDER BY `customer_name` 
DESC LIMIT 50 

查詢的這個胖男孩在我的開發機器上花費約80秒,在服務器上花約7秒鐘。

兩個問題:

  1. 我做了什麼錯此查詢? (我需要從我的錯誤中學習)
  2. 我該如何改進此查詢?
+2

如果可能的話不要使用'LIKE'。 – rekire

+3

在查詢前放置一個'EXPLAIN',然後在這裏發佈結果。 – Kermit

+0

只有'選擇'你需要的列!千萬不要'SELECT *'。 – Kermit

回答

3

嘗試使用加入:

SELECT * 
FROM 
    `notes` left join orders 
    on notes.customer_email=orders.customers_email_address 
WHERE 
    orders.customers_email_address is null 
    AND notes.customers_id IS NULL 
    AND ((customer_phone LIKE '%bob%') 
     OR (customer_name LIKE '%bob%') 
     OR (customer_email LIKE '%bob%')) 
ORDER BY `customer_name` 
DESC LIMIT 50 

他們通常比IN/NOT IN子句快。而且,我也不確定你爲什麼在這裏放置一個小組。

+0

非常感謝,這完美地回答了我的問題。查詢運行時間爲.03秒! –