添加两个表值与当前日期(今天日期)

时间:2015-01-21 09:18:29

标签: php mysql sql mysqli sqlalchemy

我试图从不同的表中添加总值的总和。这个查询成功但我想要添加当前日期。

表1表2 日期Total_Cost日期Total_Cost
21/01/2015 500 21/01/2015 500

SELECT (SELECT SUM(Total_Cost) FROM Table1) + (SELECT SUM(Total_Cost) FROM Table2) as total

给出正确答案:1000

但是我使用当前日期运行此查询添加。

SELECT (SELECT SUM(Total_Cost) FROM Table1 WHERE DATE =  CURDATE()) + (SELECT SUM(Total_Cost) FROM Table2 WHERE DATE =  CURDATE()) as total

其给定值:NULL

请帮助我某人要事先解决这个问题。

1 个答案:

答案 0 :(得分:0)

您的查询需要通过使用ISNULL来处理任何一个select语句(即NULL值)不能返回任何行的可能性,例如

ISNULL(SELECT SUM(X) FROM Table1 WHERE Date=CURDATE(),0.0) 

甚至:

SELECT ISNULL(SUM(Total_Cost),0.0) FROM 
(
  SELECT Total_Cost FROM Table1 WHERE Date = CURDATE()
  UNION ALL
  SELECT Total_Cost FROM Table2 WHERE Date = CURDATE()
) S1

道歉,如果这是无效的MySQL语法我对SQL Server更熟悉,但我希望它有帮助。