加速MySQL Query inc子查询加入?

时间:2013-07-10 08:43:17

标签: mysql sql

我在下面的查询中从多个表中提取数据以创建更新:

UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid 
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;

它工作正常但是当papr_down中有大量记录时,处理需要很长时间。关于如何优化它的任何想法?

2 个答案:

答案 0 :(得分:0)

我认为电子邮件地址之间的连接是这里的问题,您可以尝试使用Id的连接。 如果您向我们提供以下查询的屏幕截图::

EXPLAIN Select * from 
en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid 

LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
WHERE sd.fieldid = 33

答案 1 :(得分:0)

据我所知,我们应该仅对SELECT子句中预设的列使用连接,对于其他连接,我们应该使用WHERE子句

来实现

请尝试以下查询:

UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls 
on sd.subscriberid = ls.subscriberid 
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down AS pd1
INNER JOIN email.papr_data AS pd2 on pd1.paper_id = pd2.id
WHERE 
email.papr_exam.id in (select exam from email.papr_data where exam = 1)
AND
email.papr_levl.id in (select level from email.papr_data where level = 4 )
AND 
email.papr_subj.id in (select subject from email.papr_data)

GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;

我无法在我的机器上执行此操作,因为我没有架构