DATEDIFF - 用NOW()替换NULL

时间:2015-12-30 08:07:55

标签: mysql date datediff

我得到了以下SQL查询

SELECT
    e.id,
    c.name,
    e.location,
    e.designation,
    e.time_period_from,
    e.time_period_to,
    DATEDIFF(e.time_period_to, time_period_from) AS tenure_in_days
FROM
    employment e
LEFT JOIN
    company c ON (c.id = e.company_id)
LIMIT
    0, 10

这很有效,我的情况是time_period_to可以有NULL个值,在这种情况下,我想用当前日期替换它。

这是我试过的。

SELECT
    e.id,
    c.name,
    e.location,
    e.designation,
    e.time_period_from,
    e.time_period_to,
    DATEDIFF(IF(ISNULL(e.time_period_to), NOW(), e.time_period_from)) AS tenure_in_days
FROM
    employment e
LEFT JOIN
    company c ON (c.id = e.company_id)
LIMIT
    0, 10

这给了我以下错误

ERROR 1582 (42000): Incorrect parameter count in the call to native function 'DATEDIFF'

我哪里错了?

2 个答案:

答案 0 :(得分:2)

改为使用COALESCE

SELECT
    e.id,
    c.name,
    e.location,
    e.designation,
    e.time_period_from,
    e.time_period_to,
    DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from) AS tenure_in_days
FROM employment e
LEFT JOIN company c ON (c.id = e.company_id)
LIMIT 0, 10

我猜你想要DATEDIFF(e.time_period_to, e.time_period_from)

使用LIMIT而不使用显式ORDER BY可能会返回依赖于执行计划的结果。

答案 1 :(得分:2)

你的括号在错误的地方。不要将e.time_period_from指定为DATEDIFF的第二个参数,而是将其作为IF的第三个参数。它应该是:

DATEDIFF(IF(ISNULL(e.time_period_to), NOW(), e.time_period_to), e.time_period_from) AS tenure_in_days

您还可以使用IFNULL(这是COALESCE的更简单版本,名称更为助记符):

DATEDIFF(IFNULL(e.time_period_to, NOW()), e.time_period_from) AS tenure_in_days