有一物品表,其一列为颜色,求表中颜色为红和蓝色的物品和,脚本:spa
select sum(if(color='blue',1,0)) as blue,sum(if(color='red',1,0)) as red from products;字符串
注:select
IF(exPR1,expr2,expr3)
若是 expr1 是TRUE (expr1 <> 0 and expr1 <> NULL),则 IF()的返回值为expr2; 不然返回值则为 expr3。IF() 的返回值为数字值或字符串值,具体状况视其所在语境而定。脚本
上述也能够使用count查询,如:查询
select count(color='blue' or null) as blue,count(color='red' or null) as red from products;co
使用了count进行查询并保证若没有相应的颜色,表达式的值为null字符