sql語句裏面用mysql函數的血淚教訓

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。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章