- 在mysql中if()函数的用法类似于java中的三目表达式,其用处也比较多,具体语法如下:
IF(expr1,expr2,expr3),如果expr1的值为true,则返回expr2的值,如果expr1的值为false,
则返回expr3的值。
mysql> select name,if(sex=0,'女','男') as sex from student;+-------+-----+| name | sex |+-------+-----+| name1 | 女 || name2 | 女 || name3 | 男 || name4 | 女 |+-------+-----+4 rows in set (0.00 sec)复制代码
其也经常用到判断的关联条件中,其示例如下:
SELECT s.SCHOOL_CITY as schoolCity, s.SCHOOL_COUNTY as schoolCounty, count(DISTINCT `s`.`SCHOOL_ID`) as schoolNum, sum(m.duration) as sumDuration, sum(`m`.`VIEWERCOUNT`) as viewLiveSum, sum(m.replayViewerCount)as reViewSum, sum(m.praisecount) as sumpraise, sum(`m`.`VIEWERCOUNT`+m.replayViewerCount) as viewSum from ((tbl_hbb_mobile_live_statistics m join tbl_hbb_resource_visit_map v) join tbl_school_info s) where`m`.`RESOURCEID`= `v`.`RESOURCEID` and if((`v`.`rangeTYPE`= '2'),(`v`.`rangeID`= `s`.`SCHOOL_ID`),(`v`.`parentId`= `s`.`SCHOOL_ID`))复制代码
- 在mysql中sum()
sum (column ) : 把一列的值全部相加 复制代码
- sum()与if()联合使用
sum (column ) : 把一列的值全部相加 sum( if ( 条件 , 2 , 0 ) ) : 满足“条件”,加2,不满足条件,加0复制代码
例:表user如图
统计每个用户count<5的次数select user_id,sum(IF(count<5,1,0)) as times from user group by user_id;复制代码