DATEDIFF - 将 NULL 替换为 NOW()
DATEDIFF - Replace NULL with NOW()
我得到了关注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'
我哪里错了?
改用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)
。
使用没有显式 ORDER BY
的 LIMIT
可能 return 结果取决于执行计划。
你的括号放错地方了。您没有将 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
我得到了关注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'
我哪里错了?
改用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)
。
使用没有显式 ORDER BY
的 LIMIT
可能 return 结果取决于执行计划。
你的括号放错地方了。您没有将 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