Optimize SQL with if or case when

1. [Basic query statement display optimization]

#Query by type
SELECT id,title,type FROM table WHERE type=1;
SELECT id,title,type FROM table WHERE type=2;

 optimize with if

#if(expr,true,false)
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;

 Optimize with case when

#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;

 

2. [Statistical data performance optimization]

#Query the quantity under different conditions twice
SELECT count(id) AS size FROM table WHERE type=1
SELECT count(id) AS size FROM table WHERE type=2

 optimize with if

#sum method
SELECT sum(if(type=1, 1, 0)) as type1, sum(if(type=2, 1, 0)) as type2 FROM table
#count method
SELECT count(if(type=1, 1, NULL)) as type1, count(if(type=2, 1, NULL)) as type2 FROM table
#The time to test the two is about the same
#It is recommended to use sum, because if you don't pay attention, count will count 0 in the false of if

 Optimize with case when

#sum
SELECT 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

 The time of the pro-test query twice and the optimized query once is the same, and the optimization time is 1/2

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993293&siteId=291194637