欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MySQL max函数优化

程序员文章站 2024-03-25 13:38:28
...

测试环境:

MySQL max函数优化

测试Sql:

select max(sscode) from	sm_sku_show where del_flag = "0";
select sscode from sm_sku_show where del_flag = "0" order by sscode desc limit 1;
测试耗时:

[SQL]
select max(sscode) from	sm_sku_show where del_flag = "0";
受影响的行: 0
时间: 19.503s

[SQL]
select sscode from sm_sku_show where del_flag = "0" order by sscode desc limit 1;
受影响的行: 0
时间: 0.001s
测试结果:

+---------------------+
| max(sscode)         |
+---------------------+
| SS20180120101925999 |
+---------------------+
1 row in set

+---------------------+
| sscode              |
+---------------------+
| SS20180120101925999 |
+---------------------+
1 row in set
结论:

max() 函数的需扫描where条件过滤后的所有行。

请慎用max()函数,特别是频繁执行的sql,若需用到可转化为测试中的  order by id desc limit 1