2012-06-15 61 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