2012-06-15 93 views
1

我這是基於以下SQL查詢產生的下拉列表:優化MySQL的NOT IN查詢


SELECT * FROM product WHERE 
    product.id NOT IN (SELECT customer_1.product_id FROM customer_1 WHERE (customer_1.product_id != '$x')) 
AND product.id NOT IN (SELECT customer_2.product_id FROM customer_2 WHERE (customer_2.product_id != '$x')) 
AND product.id NOT IN (SELECT customer_3.product_id FROM customer_3 WHERE (customer_3.product_id != '$x')); 

即就出現在這裏是執行時間的問題。這個查詢本身大約需要5.3秒。我在同一頁面上有幾個其他類似的查詢。

我的問題是:是否有實現相同結果的更好,更快的方式?

預先感謝您。

回答

2

您可能會從LEFT JOIN s獲得更好的性能,在連接的右側(customer_*表)查找NULL。如果我明白你的目標,這應該做的工作:

SELECT 
    products.* 
FROM 
    products 
    LEFT JOIN customer_1 ON products.id = customer_1.product_id 
    LEFT JOIN customer_2 ON products.id = customer_2.product_id 
    LEFT JOIN customer_3 ON products.id = customer_3.product_id 
WHERE 
    products.id != '$x' 
    AND customer_1.product_id IS NULL 
    AND customer_2.product_id IS NULL 
    AND customer_3.product_id IS NULL 
+1

非常感謝你。那就是訣竅。執行時間降至0.7123秒。 – Madi

1

你應該使用NOT EXISTS。有了正確的索引表,這種情況下它可以顯著更快。

1
SELECT * FROM product Left join (SELECT customer_1.product_id FROM customer_1 WHERE (customer_1.product_id != '$x')) as t1 Left join (SELECT customer_2.product_id FROM customer_2 WHERE (customer_2.product_id != '$x')) as t2 left join (SELECT customer_3.product_id FROM customer_3 WHERE customer_3.product_id != '$x')) as t3 
And t3.product_id is null and t1.product_id is null and t2.product_id is null