2016-07-22 68 views
0

我有以下查詢MySQL查詢凍結

SELECT DISTINCT 
    Products.Product_name 
    FROM Order_details 
    INNER JOIN Products 
    ON Products.Product_codenumber = Order_details.Product_codenumber 
    INNER JOIN Orders 
    ON Order_details.Order_ID = Orders.Order_ID 
    INNER JOIN Customers 
    ON Orders.Customer_ID = Customers.Customer_ID 
    INNER JOIN Discount_cards 
    ON Discount_cards.Phone_number = Customers.Login 
    WHERE Orders.Status_ID = '5' 
    AND (DATE(Orders.Time) BETWEEN '$start_date' AND '$end_date') 

,旨在使我得到我的範圍,或者從訂單信息,優惠卡的用戶訂購的產品。當我第一次寫它時,它似乎工作正常,但最近我被告知它凍結了,我不知道爲什麼。我試着玩一下它,似乎當我添加日期範圍,或者甚至只是單一的日期搜索條件時,它會凍結(可以在PHPMyAdmin中永久顯示'Loading'彈出窗口);除此之外,執行大約需要1秒。

Here's what EXLAIN gives me.

+0

你爲什麼在外部查詢中使用distinct。在內部查詢中試用它,您認爲可能出現的重複來自 – Avi

+0

如果我們沒有從那裏獲取任何列,我們爲什麼要加入Customer和Discount_Card表? – Avi

+0

你如何執行這個,使用PHP? –

回答

0

好吧,顯然拋出內加入了Discount_cards並用WHERE替代它修復了這個問題:

SELECT DISTINCT 
    Products.Product_name 
    FROM Order_details 
    INNER JOIN Products 
    ON Products.Product_codenumber = Order_details.Product_codenumber 
    INNER JOIN Orders 
    ON Order_details.Order_ID = Orders.Order_ID 
    INNER JOIN Customers 
    ON Orders.Customer_ID = Customers.Customer_ID 
    WHERE 
    Customers.Login IN (
     SELECT 
     Phone_number 
     FROM Discount_cards 
     ) 
    AND Orders.Status_ID = '5' 
    AND (DATE(Orders.Time) BETWEEN '$start_date' AND '$end_date') 

我不知道爲什麼這樣做,凍結,雖然發生了,解釋將不勝感激。