SQL中count(*)、count(字段)、count(distinct字段)的区别
Contents
SQL中count(*)、count(字段)、count(distinct字段)的区别
count() 是MySQL内置函数,用来统计字段中非NULL的数量
- count(*) 统计表的行数
- count(1)count(0)的效果都是一样的,返回表的行数
- count(字段) 统计字段中非NULL的数量
- count(distinct 字段) 统计字段中不重复,且不为NULL的数量
innoDB中的性能区别
效率从高到低: count(*) ≈ count(1) > count(主键id) > count(字段)
建议使用count(1),语文更清晰。
- count(*) 做了内部优化,会自动使用索引
- count(1) innoDB遍历全表,但不取出字段值
- count(主键) innoDB遍历全表,并取出主键值
- count(字段) innoDB遍历全表,判断是否为NULL