在mysql上双重加入双重计数?

时间:2012-04-15 03:28:41

标签: mysql sql

select SQL_NO_CACHE a.id,
       date_format(a.data_cron,'%d/%m/%Y às %H:%i:%s') as data_pt,a.msgal,
       a.status,
       b.nome,
       c.msg,
       if((select count(*) from moips_temps where envio_id=a.id group by envio_id) > 0,1,0) as senvio,
       if((select count(*) from moips_temps2 where envio_id=a.id group by envio_id) > 0,1,0) as senvio2 
  from moips_envios a, 
       moips_listas b, 
       moips_msgs c 
 where a.lista_id = b.id 
   and a.msg_id = c.id 
   and a.moips_id = 44 
order by a.id desc

时间:0.0146

select SQL_NO_CACHE a.id,date_format(a.data_cron,'%d/%m/%Y às %H:%i:%s') as data_pt, a.msgal, a.status, b.nome, c.msg, 
  if(count(d.envio_id) > 0,1,0) as senvio,
  if(count(e.envio_id) > 0,1,0) as senvio2 
from moips_envios a 
left join moips_temps d 
  on a.id=d.envio_id 
left join moips_temps2 e 
  on a.id=e.envio_id, moips_listas b, moips_msgs c 
where a.lista_id=b.id 
  and a.msg_id=c.id 
  and a.moips_id=25 
group by a.id 
order by a.id desc

时间:0.1107

为什么使用子查询计数更快?

1 个答案:

答案 0 :(得分:0)

非常简单的改进,非标准的,仅在MySQL中可用,正在改变:

GROUP BY a.id 
ORDER BY a.id DESC

为:

GROUP BY a.id DESC