Error when selecting a DATEDIFF in the IF condition
source link: https://www.codesd.com/item/error-when-selecting-a-datediff-in-the-if-condition.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Error when selecting a DATEDIFF in the IF condition
In a MySQL query, I am trying to select either a DATEDIFF()
or NOW()
based on an IF()
condition. The behavior of MySQL is confusing me here.
This query run in phpMyAdmin has some strange results. The values should be identical, but they are not.
SELECT
TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW()) AS `A`,
IF(FALSE, NOW(), TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`
A ----------------- | B -----------------
01:00:00 ---------- | 2001-00-00 00:00:00
If I try this query, changing NOW()
to NULL
in the first option of the IF
condition, it shows the proper result for the TIMEDIFF
. Why is this?
SELECT
TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW()) AS `A`,
IF(FALSE, NULL, TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`
A ----------------- | B -----------------
01:00:00 ---------- | 01:00:00
So then my question is: how is NOW()
versus NULL
affecting the IF
return?
May be NOW()
or other date functions have to return a value in all cases, because I was testing the same query with RAND()
and SQRT()
functions but in that case it is returning the correct value, so may be the issue is with NOW()
function return value
TRY using NOW()
with a blank CONCAT()
,it won't manipulate your return value also, and it worked well both with TRUE
and FALSE
SELECT
TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW()) AS `A`,
IF(TRUE, CONCAT(NOW()), TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`
SELECT TIMEDIFF( DATE_ADD( NOW( ) , INTERVAL 1 HOUR ) , NOW( ) ) AS `A` ,
CASE WHEN TRUE THEN TIMEDIFF( DATE_ADD( NOW( ) , INTERVAL 1 HOUR ) , NOW( ) )
ELSE CONCAT( NOW( ) )
END AS `B
both gave correct result
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK