MySQL查询重新设计

时间:2012-11-28 18:59:08

标签: mysql

我有以下查询从notes表中选择输入(例如:bob)不在orders表中的所有内容。

SELECT * FROM `notes` WHERE notes.customer_email NOT IN 
(SELECT customers_email_address FROM orders) 
AND ((customer_phone LIKE '%bob%') 
OR (customer_name LIKE '%bob%') 
OR (customer_email LIKE '%bob%')) 
AND customers_id IS NULL 
GROUP BY `customer_email` 
ORDER BY `customer_name` 
DESC LIMIT 50

这个查询的胖男孩在我的开发机器上花费约80秒,在实时服务器上花费约7秒。

两个问题:

  1. 这个查询我做错了什么? (我需要从错误中吸取教训)
  2. 如何改进此查询?

1 个答案:

答案 0 :(得分:3)

尝试使用联接:

SELECT *
FROM
  `notes` left join orders
   on notes.customer_email=orders.customers_email_address
WHERE
  orders.customers_email_address is null
  AND notes.customers_id IS NULL 
  AND ((customer_phone LIKE '%bob%') 
        OR (customer_name LIKE '%bob%') 
        OR (customer_email LIKE '%bob%')) 
ORDER BY `customer_name` 
DESC LIMIT 50

它们通常比IN / NOT IN子句更快。而且,我不知道为什么你在这里放一个group by子句。