CONCAT()和DATE_FORMAT()在日期范围的mysql中给出不同的结果

时间:2017-06-01 21:38:56

标签: mysql date-format concat

我遇到了麻烦,当我使用CONCAT('2017-01-15', ' 00:00:00')时,它给出的结果与我在MySQL中使用DATE_FORMAT('2017-01-15', ' %Y-%m-%d 00:00:00')日期范围时的结果不同。有什么想法吗?

例如我的查询是

SELECT SUM(payments) as pays 
FROM   table 
WHERE  employee_id = 25 
AND    `date` >= DATE_FORMAT('2017-05-16', '%Y-%m-%d 00:00:00') 
AND    `date` <= DATE_FORMAT('2017-05-31', '%Y-%m-%d 23:59:59') 
GROUP BY employee_id 
ORDER BY id DESC

和CONCAT

SELECT SUM(payments) as pays 
FROM   table 
WHERE  employee_id = 25 
AND    `date` >= CONCAT('2017-05-16', ' 00:00:00') 
AND    `date` <= CONCAT('2017-05-31', ' 23:59:59') 
GROUP BY employee_id 
ORDER BY id DESC

两者都有不同的结果..

2 个答案:

答案 0 :(得分:0)

我刚刚注意到您在我复制粘贴的格式字符串中有前导空格。请仔细检查您的实际查询。

[无视以下]

这可能是一个奇怪的转换问题,看来DATE_FORMAT(在我正在测试的服务器上)包含一个领先的空间。

如果您有兴趣,这是我用来追踪这种陌生感的查询:

SELECT @t0 := '2017-01-15' AS t0, @tN := '2018-01-15' AS tN
, @df0 := DATE_FORMAT(@t0, ' %Y-%m-%d 00:00:00') AS df0, @dfN := DATE_FORMAT(@tN, ' %Y-%m-%d 00:00:00') AS dfN
, @ct0 := CONCAT(@t0, ' 00:00:00') AS ct0, @ctN := CONCAT(@tN, ' 23:59:59') AS ctN
, @df0 = @ct0 AS eq0, @dfN = @ctN AS eqN
, CAST(@ct0 AS DATETIME) = CAST(@df0 AS DATETIME) AS castsEqual0
, @ct0 = CAST(@df0 AS DATETIME) AS castDF0Equal
, CAST(@ct0 AS DATETIME) = @df0 AS castCT0Equal
, @n := CAST(now() AS DATETIME) AS n
, @n > @ct0 AS `n>ct0`, @n > @df0 AS `n>df0`
, @n < @ctN AS `n<ctN`, @n < @dfN AS `n<dfN`
, @n < CAST(@dfN AS DATETIME) AS `n<castDFN`
, CAST(@n AS CHAR) < @dfN AS `castN<dfN`
, LENGTH(CAST(@n AS CHAR)), LENGTH(@dfN)
, CONCAT('[', @dfN, ']')
;

答案 1 :(得分:0)

感谢响应guyz,实际上我在23:23:59发出问题:)它必须是23:59:59 :)我没有注意到它... 谢谢 - 问题解决了