php - 比较年份,用substr截取前4位快,还是date('Y')快?

查看:102
本文介绍了php - 比较年份,用substr截取前4位快,还是date('Y')快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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' ";
    }

解决方案

不管是用substr截取前4位,还是date('Y'),你都是php的执行而已,php这点时差忽略不记,最终得到的sql是一样的,并不会影响到数据库的查询效率。

你应该贴出需要执行的sql语句来让大家看看是否能再优化

这篇关于php - 比较年份,用substr截取前4位快,还是date('Y')快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆