Home > Backend Development > PHP Tutorial > 一条SQL执行多次 sum 特别慢

一条SQL执行多次 sum 特别慢

WBOY
Release: 2016-06-06 20:29:55
Original
1796 people have browsed it

<code>SELECT agentid,count(id) AS allnum,
    sum(if(review_flag = 'p'AND delflag IN ('N' , 'P'),1,0)) AS approved_1,
    sum(if(review_flag = 'E', 1, 0)) AS approved_2,
    sum(if(review_mode = '3' AND review_flag = 'Y',1,0)) AS approved_3,
    sum(if(review_mode = '2' AND review_flag = 'Y',1,0)) AS approved_4,
    sum(if(review_mode = '1' AND review_flag = 'Y',1,0)) AS approved_5,
    sum(if(review_flag = 'N' AND resubmit = 'Y',1,0)) AS approved_6,
    sum(if(review_flag = 'N' AND resubmit = 'N',1,0)) AS approved_7
    FROM talbe WHERE agentid IN ('A' , 'B', 'C') AND delflag IN ('N' , 'P', 'H') 
    GROUP BY agentid

      
该语句执行的时候 需要20多S才完成。
</code>
Copy after login
Copy after login

回复内容:

<code>SELECT agentid,count(id) AS allnum,
    sum(if(review_flag = 'p'AND delflag IN ('N' , 'P'),1,0)) AS approved_1,
    sum(if(review_flag = 'E', 1, 0)) AS approved_2,
    sum(if(review_mode = '3' AND review_flag = 'Y',1,0)) AS approved_3,
    sum(if(review_mode = '2' AND review_flag = 'Y',1,0)) AS approved_4,
    sum(if(review_mode = '1' AND review_flag = 'Y',1,0)) AS approved_5,
    sum(if(review_flag = 'N' AND resubmit = 'Y',1,0)) AS approved_6,
    sum(if(review_flag = 'N' AND resubmit = 'N',1,0)) AS approved_7
    FROM talbe WHERE agentid IN ('A' , 'B', 'C') AND delflag IN ('N' , 'P', 'H') 
    GROUP BY agentid

      
该语句执行的时候 需要20多S才完成。
</code>
Copy after login
Copy after login

  1. 调整表结构. 似乎你把很复杂的逻辑放在 数据表结构里了.

  2. 多次sum不是问题. 主要在于这个group by上, 一般的, mysql 全表扫一边, 创建临时表, 排序分组. 这个是很慢的. 你可以试一下 建立 (agentid, delflag, review_flag, review_mode, resubmit, id) 的联合索引.

索引,从新设计你自己标的结构。。。怎么会sum这么多次。。。

这不是sum的问题啊,这条语句本来就复杂。

这种情况我想应该是索引建立的不够科学吧,你可以借助EXPLAIN来具体查看什么地方会卡住,是否用到索引。
同时,给你一个建议,你应该把表结构贴出来,这样路过的大神就能具体帮你分析分析了。

先分组 sum,把结果取到你的程序里去继续加工

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template