MySQL多个SELECT不工作

时间:2015-11-13 11:17:03

标签: mysql sql

我正在尝试将不同表中的总计总和选择为一个查询。出于某种原因,下面的查询曾经工作但现在返回NULL。如果我执行单个查询,它们会返回一个总和,但不会将它们一起添加。任何人都可以看到我做错了什么?

SELECT
(
        (SELECT SUM(a.Total) FROM table1 a) + 
        (SELECT SUM(c.Total) FROM table2 c) + 
        (SELECT SUM(eb.Total) FROM table3 eb) + 
        (SELECT SUM(h.Amount) FROM table4 h) + 
        (SELECT SUM(n.Total) FROM table5 n) + 
        (SELECT SUM(mbo.Total) FROM table6 mbo)
   )
AS Overral_Amount_Total

2 个答案:

答案 0 :(得分:2)

您可以使用子查询:

SELECT SUM(sub.col) AS Overral_Amount_Total
FROM
(
  SELECT SUM(Total) AS col FROM table1 
  UNION ALL
  SELECT SUM(Total) FROM table2
  UNION ALL
  SELECT SUM(Total) FROM table3
  UNION ALL
  SELECT SUM(Amount) FROM table4
  UNION ALL
  SELECT SUM(Total) FROM table5
  UNION ALL
  SELECT SUM(Total) FROM table6
) AS sub;

重点是(您的某个表为空/包含特定列中的所有NULL):

CREATE TABLE tab(col INT);

SELECT SUM(col)
FROM tab;
-- will return NULL

SqlFiddleDemo

对于空表,它将返回NULL,添加到NULL的任何内容都为NULL

答案 1 :(得分:1)

您的标量子查询始终返回一行。这意味着您还可以在子查询中使用get 'old-page', to: redirect { |_, _| Rails.application.routes.url_helpers.new_page_path }

COALESCE()

如果您的实际查询使用相关子查询,这可能非常方便。与SELECT ( (SELECT COALESCE(SUM(a.Total), 0) FROM table1 a) + (SELECT COALESCE(SUM(c.Total), 0) FROM table2 c) + (SELECT COALESCE(SUM(eb.Total), 0) FROM table3 eb) + (SELECT COALESCE(SUM(h.Amount), 0) FROM table4 h) + (SELECT COALESCE(SUM(n.Total), 0) FROM table5 n) + (SELECT COALESCE(SUM(mbo.Total), 0) FROM table6 mbo) ) AS Overall_Amount_Total 解决方案相比,此解决方案实现起来要简单得多。