mysql查询持续时间超过300秒,超过20秒获取,架构中只有500k行

时间:2016-08-17 15:17:20

标签: mysql

我花了很多时间试图弄清楚如何使这个查询起作用。既然我有一个有效的查询,那就太长了。

有谁可以帮助我了解更好和/或更快的方法来实现相同的查询结果?

select 
  a.customer_id, 
  a.id aid, 
  p.id payid, 
  p.amount 
from 
  agreement a 
left join 
  payment p 
on 
  a.customer_id = p.customer_id 
where 
  p.customer_id is null 
  and a.campaign = "vsf" 
  and a.customer_id in 
    ( SELECT a1.customer_id 
    FROM agreement a1 
    GROUP BY a1.customer_id 
    HAVING COUNT(a1.id) >= 2 ) 

1 个答案:

答案 0 :(得分:0)

您不需要选择p.id payi和p.amount,因为使用左连接和where .. null您将获得协议中存在且在付款中不存在的行 你能尝试一下:

select * from (SELECT a1.customer_id , a1.id aid
    FROM agreement a1 
    where a.campaign = "vsf" 
    GROUP BY a1.customer_id 
    HAVING COUNT(a1.id) >= 2) as t
left join 
  payment p 
on 
  t.customer_id = p.customer_id 
where 
  p.customer_id is null