1问题描述:根据始末日期查询数据,由于数据库数据量大,用between and很慢,就添加了year,month,day字段,在比较年月日的时候有substr和date两种方法,两种都尝试过每次加载时间都在变化,也没找到相关的技术文章。理论上是两种速度都差不多,还是有相对快的方法?感谢每一个答题者。
2.相关代码片段:
//substr
if(substr($startTime,0,4) == substr($endTime,0,4)){
$str .= " L.year = ".substr($startTime,0,4);
if(substr($startTime,4,2) == substr($endTime,4,2)){
$str .= " and L.month = ".substr($startTime,4,2);
if(date('Ynd',strtotime($startTime)) == date('Ynd',strtotime($endTime))){
$str .= " and day = ".date('d',strtotime($startTime));
}else{
$str .= " and log_date between '$startTime' and '$endTime' ";
}
}else{
$str .= " and log_date between '$startTime' and '$endTime' ";
}
}else{
$str .= " L.log_date between $startTime and $endTime";
}
//date
if(date('Y',strtotime($startTime)) == date('Y',strtotime($endTime))){
$str = " where year = ".date('Y',strtotime($startTime));
if(date('Yn',strtotime($startTime)) == date('Yn',strtotime($endTime))){
$str .= " and month = ".date('n',strtotime($startTime));
if(date('Ynd',strtotime($startTime)) == date('Ynd',strtotime($endTime))){
$str .= " and day = ".date('d',strtotime($startTime));
}else{
$str .= " and log_date between '$startTime' and '$endTime' ";
}
}else{
$str .= " and log_date between '$startTime' and '$endTime' ";
}
}else{
$str = " where log_date between '$startTime' and '$endTime' ";
}
给我你的怀抱2017-05-16 13:11:05
substr을 사용하여 처음 4자리를 가로채거나 날짜('Y')를 사용하든 PHP의 시간 차이를 무시하면 됩니다. 최종 SQL은 동일하며 데이터베이스 쿼리 효율성에 영향을 미치지 않습니다.
실행해야 할 SQL 문을 최적화할 수 있는지 모두가 볼 수 있도록 게시해야 합니다
巴扎黑2017-05-16 13:11:05
인덱스와 테이블 구조가 최적화되어 있지 않은 경우 먼저 최적화하면 속도가 많이 향상됩니다. 그렇지 않으면 테이블을 분할하는 것을 고려해보세요.
我想大声告诉你2017-05-16 13:11:05
연도 검색을 직접 작성해서 성능 개선이 있는지 확인해 보시는 것이 좋을 것 같습니다. 이런 경우에는 프런트에서 직접 원하는 값을 전달해주시면 됩니다
过去多啦不再A梦2017-05-16 13:11:05
이 두 가지 방법의 실행 효율성에는 변화가 없습니다. PHP는 sql 문을 함께 연결합니다. 데이터베이스 또는 sql 문에서 최적화하는 방법을 찾아야 합니다.