sql语句里面用mysql函数的血泪教训

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43740552/article/details/102675693

sql语句如下:

$sql = "select * from sdb_b2c_orders where salearea_id={$cityId} and memo like '%$saleName%' and from_unixtime(ship_time,'%Y-%m-%d')='$ship_date'";

sdb_b2c_orders表里有400万数据,这条sql尽然跑了22秒,好可怕。。。,最后发现性能问题出在from_unixtime函数上面,看来sql语句里面真的是不能用函数。

解决方法:
因为ship_time在数据库里存储的是时间戳,而$ship_date是日期,所以我只需要把$ship_date转成时间戳,然后用between就可以解决这个问题。
$startTimestamp = strtotime($ship_date);
$endTimestamp = $startTimestamp + 86400;
$sql = "select * from sdb_b2c_orders where salearea_id={$cityId} and memo like '%$saleName%' and ship_time between $startTimestamp and $endTimestamp";

修改之后这条sql的运行时间不到1s。

猜你喜欢

转载自blog.csdn.net/weixin_43740552/article/details/102675693