我有一个下拉列表,它是根据以下sql查询生成的:
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秒。我在同一页面上有几个其他类似的查询。
我的问题是:是否有更好,更快的方法来实现相同的结果?
提前谢谢。
答案 0 :(得分:2)
您可以从LEFT JOIN
获得更好的性能,在联接的右侧查找NULL(customer_*
表)。如果我了解你的目标,那就应该做好这个工作:
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 :(得分:1)
您应该使用NOT EXISTS
。使用正确索引的表格,这种情况可以明显加快。
答案 2 :(得分: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