drnrxv9383 2013-08-01 00:19
浏览 349
已采纳

MySQL替换sum(if(xxx,1,0))

Hi I need some help optimizing this code, currently it takes 38 seconds to run the SQL query, and 23 to load it as a view. Here's the background - Redirects table records when a member uses a link and records where they go, and when they return and with what status. Projects table manages the per project information that I need. Currently I do have a third table that keeps a per project count which is updated each time a record is added to the redirects table, however the counts can be a little unreliable. Every hour the server runs the query to fix/verify the counts.

Is there any good way to count the columns without having to use a sum(if(xxx,1,0)) ?

Select projects.ID as ID,cid,name as name,state as status,
                sum(if(status="complete",1,0)) as complete,cpc,
                cpc*ss as mmkingaku,
                cpc*sum(if(status="complete",1,0)) as total,
                sum(if(status="screenout",1,0)) as screenout,
                sum(if(status="quotafull",1,0)) as quotafull, 
                sum(if(status="short",1,0)) as short,
                sum(if(status="gate",1,0)) as gate,
                sum(if(status is null,1,0)) as empty,
                sum(if(status="complete",1,0))/(sum(if(status="complete",1,0))+sum(if(status="screenout",1,0)))*100 as IR
                from redirects,projects
                where redirects.rid=projects.rid and state<>"test" group by name order by cid desc
  • 写回答

1条回答 默认 最新

  • dougu2006 2013-08-01 00:24
    关注

    SQL performance is not usually due to calculations in the select clause. You need to look at the from and group by clauses.

    Do your tables have appropriate indexes? You should have an index on redirects.rid, projects.rid, or both. In fact, these should probably be composite indexes, including state and test (wherever is appropriate).

    The group by can be a performance hog in MySQL. How much data is in each table?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog