IFNULL不像我想的那样工作

时间:2015-03-13 20:31:38

标签: mysql sql ifnull

我有两个可以为空的DATE字段(PublishFrom,PublishTo)。 我试图通过此查询获取记录:

SELECT * FROM tblNews 
    WHERE Publish = 1 
    AND IFNULL(PublishFrom, CURDATE() - INTERVAL 1 DAY) <= "2015-03-13" 
    AND IFNULL(PublishTo, CURDATE() + INTERVAL 1 DAY) >= "2015-03-13" 
    ORDER BY DateCreated DESC'

意思是如果这些字段中的(一个)字段的值为空,则将其替换为昨天的值和/明天的值,以便始终显示该条目。

现在我只看到PublishFrom和/或PublishTo不为空的帖子。怎么样?

2 个答案:

答案 0 :(得分:2)

使用CURDATE() + 1- 1会转换CURDATE并搞砸比较。 Instead use + INTERVAL 1 DAY (or - INTERVAL 1 DAY)

答案 1 :(得分:0)

为什么不使用显式逻辑?

SELECT *
FROM tblNews 
WHERE Publish = 1  AND
     (PublishFrom <= '2015-03-13' OR PublishFrom IS NULL) AND
     (PublishTo >= '2015-03-13' OR PublishTo IS NULL)
ORDER BY DateCreated DESC