MySQL中count(*)、count(1)和count(col)的区别汇总
前言
count函数是用来统计表中或数组中记录的一个函数,count(*)它返回检索行的数目,不论其是否包含NULL值。最近感觉大家都在讨论count的区别,那么我也写下吧:欢迎留言讨论,话不多说了,来一起看看详细的介绍吧。
1、表结构:
dba_jingjing@3306>[rds_test]>CREATETABLE`test_count`( ->`c1`varchar(10)DEFAULTNULL, ->`c2`varchar(10)DEFAULTNULL, ->KEY`idx_c1`(`c1`) ->)ENGINE=InnoDBDEFAULTCHARSET=utf8; QueryOK,0rowsaffected(0.11sec)
2、插入测试数据:
dba_jingjing@3306>[rds_test]>insertintotest_countvalues(1,10);
QueryOK,1rowaffected(0.03sec)
dba_jingjing@3306>[rds_test]>insertintotest_countvalues(abc,null);
ERROR1054(42S22):Unknowncolumn'abc'in'fieldlist'
dba_jingjing@3306>[rds_test]>insertintotest_countvalues('abc',null);
QueryOK,1rowaffected(0.04sec)
dba_jingjing@3306>[rds_test]>insertintotest_countvalues(null,null);
QueryOK,1rowaffected(0.04sec)
dba_jingjing@3306>[rds_test]>insertintotest_countvalues('368rhf8fj',null);
QueryOK,1rowaffected(0.03sec)
dba_jingjing@3306>[rds_test]>select*fromtest_count;
+-----------+------+
|c1|c2|
+-----------+------+
|1|10|
|abc|NULL|
|NULL|NULL|
|368rhf8fj|NULL|
+-----------+------+
4rowsinset(0.00sec)
测试:
dba_jingjing@3306>[rds_test]>selectcount(*)fromtest_count;
+----------+
|count(*)|
+----------+
|4|
+----------+
1rowinset(0.00sec)
EXPLAIN:{
"query_block":{
"select_id":1,
"message":"Selecttablesoptimizedaway"
1rowinset,1warning(0.00sec)
dba_jingjing@3306>[rds_test]>selectcount(1)fromtest_count;
+----------+
|count(1)|
+----------+
|4|
+----------+
1rowinset(0.00sec)
EXPLAIN:{
"query_block":{
"select_id":1,
"message":"Selecttablesoptimizedaway"
1rowinset,1warning(0.00sec)
dba_jingjing@3306>[rds_test]>selectcount(c1)fromtest_count;
+-----------+
|count(c1)|
+-----------+
|3|
+-----------+
1rowinset(0.00sec)
"table":{
"table_name":"test1",
"access_type":"index",
"key":"idx_c1",
"used_key_parts":[
"c1"
],
"key_length":"33",
那么这里面的"key_length":"33",为什么是33呢,什么是二级索引?见下节
count(*)和count(1)是没有区别的,而count(col)是有区别的
执行计划有特点:可以看出它没有查询索引和表,有时候会出现selecttablesoptimizedaway不会查表,速度会很快
Extra有时候会显示“Selecttablesoptimizedaway”,意思是没有更好的可优化的了。
官方解释Forexplainsonsimplecountqueries(i.e.explainselectcount(*)frompeople)theextra
sectionwillread"Selecttablesoptimizedaway."
ThisisduetothefactthatMySQLcanreadtheresultdirectlyfromthetableinternalsandthereforedoesnotneedtoperformtheselect.
---MySQL对于“Selecttablesoptimizedaway”的含义,不是"没有更好的可优化的了",官方解释中关键的地方在于:
MySQLcanreadtheresultdirectly
所以,合理的解释是:
1数据已经在内存中可以直接读取;
2数据可以被认为是一个经计算后的结果,如函数或表达式的值;
3一旦查询的结果被优化器"预判"可以不经执行就可以得到结果,所以才有"notneedtoperformtheselect".
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。