1

我有一个基于以下 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 秒。我在同一页面上有几个其他类似的查询。

我的问题是:有没有更好更快的方法来达到同样的结果?

先感谢您。

4

3 回答 3

2

您可能会从 s 获得更好的性能,在连接(表)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
于 2012-06-15T13:38:42.800 回答
1

您可能应该使用NOT EXISTS. 使用正确索引的表,这种情况可以明显更快。

于 2012-06-15T13:39:11.020 回答
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
于 2012-06-15T13:40:07.023 回答