我有4個表(1到很多): 不要說任何關於「電子郵件」關係。這是我的開發老闆多年前建立的。MYSQL堅持生成臨時表(海量查詢)
EMPLOYEES (+-50 results)
------------------------------------------------
id name
1 EmpName 1
2 EmpName 2
CUSTOMERS (+50k results)
------------------------------------------------
id name email employee_assigned
1 John [email protected] 12
2 Donald [email protected] 6
INTERESTS_CATEGORIES (+650k results)
------------------------------------------------
id customer_email category_id
1 [email protected] 97
2 [email protected] 13
3 [email protected] 56
4 [email protected] 126
5 [email protected] 45
INTERESTS_PRODUCTS (+650k results)
------------------------------------------------
id customer_email product_id
1 [email protected] 78
2 [email protected] 23
3 [email protected] 19
4 [email protected] 56
5 [email protected] 45
所以我需要通過分配的員工和他們的興趣過濾客戶。 這裏是查詢:
SELECT
*
FROM
(
SELECT
customers.id AS 'id',
customers.name AS 'first_name',
customers.email,
employees.id AS 'employee_id'
FROM
customers,
employees
WHERE
employees.id = 2
AND
customers.employee_assigned = employees.id
) AS myCustomers
LEFT JOIN interests_categories
ON interests_categories.customer_email = myCustomers.email
LEFT JOIN interests_products
ON interests_categories.customer_email = myCustomers.email
WHERE
(
interests_categories.category_id = 20
OR
interests_categories.category_id = 21
)
GROUP BY myCustomers.email
那麼,問題:
如果員工有分配的客戶數量較少(如3)查詢 是全成。
如果員工擁有中等數量的指定客戶(超過100個)查詢夾具。
我執行SHOW PROCESSLIST,它是stucked 「生成臨時表」。
有人有想法嗎? :( 謝謝
擺脫子查詢的,只是用加入。而不是where子句中的OR,使用IN。Last請確保您在每個表的電子郵件列上以及where或ON子句中使用的任何列上都有索引。 –
我會盡力的。謝謝你的答案。 :) –