MySQL- optimize case statement

我们两清 提交于 2021-02-11 10:04:32

问题


I have a query with many case statements

    SELECT 
    case when (std_no like '070%' or std_no like '071%') then 'A'
    when (std_no like '077%' or std_no like '076%') then 'B'
    when std_no like '075%' then 'C'
    when std_no like '072%' then 'D'
    when std_no like '078%' then 'E'
    when (std_no not like '07%' and std_no not like '00%'
       and std_no not like '0100%' 
       and substring(std_no,4,1) in('2','3')) then 'F'
    when (std_no not like '07%' and std_no not like '00%' 
       and std_no not like '0100%' 
       and substring(std_no,4,1)='5') then 'G' 
    when (std_no not like '07%' and std_no not like '00%'
       and std_no not like '0100%'
      and substring(std_no,4,1)='7') then 'H'
    end as GroupName,city_id,
    count(*) as  PostCount
    from imei_tb
    where  reg_date>='2017-01-06'
    and  reg_date<='2017-01-10'
    and length(std_no)='10'
    GROUP BY GroupName,city_id
    ORDER BY city_id ASC

Is there any solution to make this query speed up ? Thanks in advance


回答1:


INDEX(reg_date) is probably the only useful index.

You are forced to do 2 sorts -- one for the GROUP BY, another for the ORDER BY.

Once I see SHOW CREATE TABLE imei_tb, I think I will be able to give you an improved query using a subquery.

New tip

One sort can be eliminated by making the GROUP BY and ORDER BY match. This should provide identical results, but faster:

GROUP BY city_id, GroupName
ORDER BY city_id, GroupName


来源:https://stackoverflow.com/questions/42224718/mysql-optimize-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!