count()函数是用来统计表中记录的一个函数,返回匹配条件的行数

image.png

count(*) count(1) sum(1)

count(*) = count(0) = count(1) =count(2) =count(常数)=sum(1)
统计表的行数,在统计结果的时候,不会忽略列值为NULL的记录

  1. select count(*), count(1), count(2) FROM teacher_student

image.png

count(列名)

统计结果的时候,会忽略列值为NULL的记录(不包括空字符串和0),即列值为NULL的记录不统计在内

  1. select count(*), count(teacher_age) FROM teacher_student

image.png

count(distinct 列名)

包括列名指定列,返回指定列的不同值的记录数,在统计结果的时候,在统计结果的时候,会忽略列值为NULL的记录(不包括空字符串和0),即列值为NULL的记录不统计在内

  1. select count(*), count(teacher_age), count(distinct teacher_age) FROM teacher_student

image.png

count(null)

count的表达式为null的话 这行不会被统计

  1. select count(null),count(if(student_score = 10,1,null)) FROM teacher_student

image.png

统计某种条件下的数量

我要统计teacher_age <= 20 的教师数量,当然下面这种写法是不对的,因为没有去重

  1. select sum(if(teacher_age <= 20, 1,0)),count(if(teacher_age <= 20, 1,null)) FROM teacher_student

image.png

统计某种条件下非重复的记录数量

满足条件取字段值,否则为空,因为count函数是不统计空值的,所以可以统计该条件下的记录数量(和上面的sum函数功能一样),如果再配合distinct关键字,就可以统计该条件下非重复的记录数量了

  1. select count(distinct if(teacher_age <= 20, teacher_id,null)) FROM teacher_student

image.png