我在SQL中有一个查询,该查询对值求和并将其添加为日期的月份。
SELECT
FROM_UNIXTIME(S.created) as start_date,
(FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
AS end_date,
FROM table1 S
LEFT JOIN table2 C ON C.id = S.id;
当这些总和中的某些值为空而不是0且我无法更改数据源时,就会出现问题。
(FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
AS end_date,
由于(C.items_left + C.items_given)
为空,所以会生成空。
所以,问题是,我该如何执行该总和以使结果为0而不是null?
答案 0 :(得分:2)
使用coalesce
SELECT
FROM_UNIXTIME(S.created) as start_date,
( coalesce(FROM_UNIXTIME(S.created),0) + INTERVAL coalesce((coalesce(C.items_left,0) + coalesce(C.items_given,0)),0) MONTH)
AS end_date,
FROM table1 S
LEFT JOIN table2 C ON C.id = S.id;
答案 1 :(得分:2)
使用COALESCE()
:
(FROM_UNIXTIME(S.created) + INTERVAL (COALESCE(C.items_left, 0) + COALESCE(C.items_given, 0)) MONTH)