使用IN优化MySQL的查询

时间:2013-05-09 07:48:41

标签: mysql performance

SELECT `listener` ,
SEC_TO_TIME( SUM( TIME_TO_SEC( `call_time` ) ) ) AS total_time,
COUNT( `listener` ) AS number
FROM calls
WHERE listened_date = '2013-05-09'
AND type in ('column1','column2')
AND id
IN ( SELECT id
FROM calls
GROUP BY CONCAT( name, ' ', when ) )
GROUP BY `listener`

此查询运行缓慢,并且其他查询无法同时运行。我该如何制作这款打火机?

我认为IN会让它变慢。在这种情况下有什么替代方案?

1 个答案:

答案 0 :(得分:2)

也许?:

SELECT c.`listener` ,
       SEC_TO_TIME(SUM(TIME_TO_SEC(c.`call_time`))) AS total_time,
       COUNT(c.`listener`) AS number
FROM calls c
WHERE c.listened_date = '2013-05-09'
  AND c.TYPE IN ('column1',
                 'column2')
  AND EXISTS (SELECT 0
              FROM calls c2
              WHERE c2.id = c.id)
GROUP BY c.`listener`