1

我有以下查询从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. 如何改进此查询?
4

1 回答 1

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 子句。

于 2012-11-28T19:21:16.497 回答