MySQL max函数优化
程序员文章站
2024-03-25 13:38:28
...
测试环境:
测试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