單個(gè)select語句實(shí)現(xiàn)MySQL查詢統(tǒng)計(jì)次數(shù)
單個(gè)select語句實(shí)現(xiàn)MySQL查詢統(tǒng)計(jì)次數(shù)的方法用處在哪里呢?用處太多了,比如一個(gè)成績單,你要查詢及格得人數(shù)與不及格的人數(shù),怎么一次查詢出來?
MySQL查詢統(tǒng)計(jì)次數(shù)簡單的語句肯定是這樣了:
- select a.name,count_neg,count_plus from
- (select count(id) as count_plus,name from score2 where score >=60 group by name) a,
- (select count(id) as count_neg,name from score2 where score <=60 group by name) b
- where a.name=b.name
即必須至少用2個(gè)語句。
今天剛好碰到發(fā)現(xiàn)mysql支持if,那就創(chuàng)造性的用if來實(shí)現(xiàn)吧:
- select name, sum(if(score>=60,1,0)),sum(if(score<60,1,0)) from score2 group by name
單個(gè)select語句實(shí)現(xiàn)MySQL查詢統(tǒng)計(jì)次數(shù)的方法簡單吧。
原理就是大于60,就賦值為1,那么sum就是計(jì)數(shù)了。
【編輯推薦】