一、[基本查詢語句展示優化]
#根據type查詢用if優化select id,title,type from table where type=1;
select id,title,type from table where type=2;
#if(expr,true,false)用case when優化select id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 from table;
select id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 from table;
#case...when...then...when...then...else...end二、[統計資料效能優化]select id,title,type,case type when 1 then 'type1' when 2 then 'type2' else 'type error' end as newtype from table;
#兩次查詢不同條件下的數量用if優化select count(id) as size from table where type=1
select count(id) as size from table where type=2
#sum方法用case when優化select sum(if(type=1, 1, 0)) as type1, sum(if(type=2, 1, 0)) as type2 from table
#count方法
select count(if(type=1, 1, null)) as type1, count(if(type=2, 1, null)) as type2 from table
#親測二者的時間差不多
#建議用sum,因為一不注意,count就會統計了if的false中的0
#sum親測查詢兩次和優化後查詢一次的時間一樣,優化時間為1/2select sum(case type when 1 then 1 else 0 end) as type1, sum(case type when 2 then 1 else 0 end) as type2 from table
#count
select count(case type when 1 then 1 else null end) as type1, count(case type when 2 then 1 else null end) as type2 from table
使用case when的心得
今天看到了這樣乙個sql語句 select top 100 from test order by case when expire date getdate then 0 else 1 end gold desc,expire date desc 剛開始我想這個sql語句最多兩個結果 1 selec...
case when語句的使用
用一條sql語句將下面scales表內的資料,查詢為圖二形式 圖一 圖二 mysql select year 年,sum case when month 1 then scale else 0 end 一月,sum case when month 2 then scale else 0 end 二月...
sql 中case when 基礎使用
sql 語句中 case when then 簡單使用 因為表很簡單,就不為大家展示建表的 了 select from user 結果如圖 when 1 then 男 when 2 then 女 else 寵物 end 性別 from user u 查詢結果如下 從中可以看出我們的case函式是作為...