mysql 时间比较 两种比较为什么有时候一样有时候不一样?

SELECT
sum(amount)
FROM
order
WHERE 1 = 1
AND commit_time >= "2017-01-01 00:00:00"
AND commit_time <= "2017-01-31 23:59:59"


SELECT
sum(amount)
FROM
order
WHERE 1 = 1
and SUBSTR(commit_time,1,10)>= "2017-01-01 00:00:00"
and SUBSTR(commit_time,1,10)<= "2017-01-31 23:59:59"

数据不多,感觉相差不大,只不过是你后面这语句多用了SUBSTR函数而已。
如果你想再优化的话,可以把commit-time >=" 2017-01-01 00:00:00 " 改成(commit-time >" 2017-01-01 00:00:00 " or commit-time =" 2017-01-01 00:00:00 " )会更快一点。

考虑下从 2017-01-31 23:59:59 到 2017-02-01 00:00:00 这一秒内的记录。上面的查询将缺少这一秒内的记录,下面的包含这一秒的记录,所以当这一秒内有记录时两种查询的结果就会不一样。

SUBSTR(time,1,10)只有年月日,后面的时分秒根本没法比较,两种写法当然不同了

第一种比第二种缺少2017-01-31 23:59:59 到 2017-02-01 00:00:00 这一秒的数据,如果第一种改为下面这样,两种的结果就一样了
SELECT
sum(amount)
FROM
order
WHERE 1 = 1
AND commit_time >= '2017-01-01 00:00:00'
AND commit_time < '2017-02-01 00-00-00';