2017-02-14 166 views
0

我有很多case語句MySQL-優化case語句

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 

有沒有什麼解決方案,使這個查詢加快查詢? 在此先感謝

+0

提供'SHOW CREATE TABLE imei_tb'的輸出 –

回答

1

`INDEX(reg_date)可能是唯一有用的索引。

你被迫做2種 - 一種爲GROUP BY,另一種爲ORDER BY

一旦我看到SHOW CREATE TABLE imei_tb,我想我可以給你一個改進的查詢使用子查詢。