联合查询返回意外结果

时间:2016-07-16 09:41:55

标签: mysql sql

我结合了两个查询来获取我所需的结果,但它没有给出我想要的结果。

查询就像这样

SELECT COALESCE(SUM(rd.AMOUNT),0) as total from revenue_d AS rd JOIN  revenue_m AS rem on rd.RV_ID = rem.RV_ID Where MONTH(rd.SCROLL_DATE) = 5   and YEAR(rd.SCROLL_DATE)= 2016

Union 

SELECT COALESCE(SUM(rd.AMOUNT),0) as total from revenue_d AS rd JOIN revenue_m AS rem on rd.RV_ID = rem.RV_ID Where MONTH(rd.SCROLL_DATE) = 6 and YEAR(rd.SCROLL_DATE)= 2016;

它给我的结果是这样的

 +---------------+
 |     total     |
 +---------------+
 |       0       |
 +---------------+

虽然我想要这样

 +---------------+
 |     total     |
 +---------------+
 |       0       |
 +---------------+
 |       0       |
 +---------------+

甚至使用了Union ALL,但仍然得到了相同的结果。

3 个答案:

答案 0 :(得分:2)

我认为总是执行最后一个查询,所以你应该这样写,

(first Query) UNION ALL (second query);

尝试此查询

(SELECT COALESCE(SUM(rd.AMOUNT),0) AS total 
    FROM revenue_d AS rd 
    JOIN  revenue_m AS rem ON rd.RV_ID = rem.RV_ID 
    WHERE MONTH(rd.SCROLL_DATE) = 5  AND YEAR(rd.SCROLL_DATE)= 2016)

  UNION ALL

(SELECT COALESCE(SUM(rd.AMOUNT),0) AS total 
    FROM revenue_d AS rd 
    JOIN revenue_m AS rem ON rd.RV_ID = rem.RV_ID 
    WHERE MONTH(rd.SCROLL_DATE) = 6 AND YEAR(rd.SCROLL_DATE)= 2016);

答案 1 :(得分:1)

您需要union allunion删除重复项,因此:

SELECT COALESCE(SUM(rd.AMOUNT),0) as total
from revenue_d rd JOIN
     revenue_m rem
     on rd.RV_ID = rem.RV_ID
Where MONTH(rd.SCROLL_DATE) = 5   and YEAR(rd.SCROLL_DATE)= 2016

Union all

SELECT COALESCE(SUM(rd.AMOUNT),0) as total
from revenue_d rd JOIN
     revenue_m rem
     on rd.RV_ID = rem.RV_ID
Where MONTH(rd.SCROLL_DATE) = 6 and YEAR(rd.SCROLL_DATE)= 2016;

但是,使用group by编写此查询更自然,但不会丢失没有值的句点:

SELECT YEAR(rd.SCROLL_DATE) as yyyy,
       MONTH(rd.SCROLL_DATE) as mm,
       COALESCE(SUM(rd.AMOUNT), 0) as total
from revenue_d rd JOIN
     revenue_m rem
     on rd.RV_ID = rem.RV_ID
Where MONTH(rd.SCROLL_DATE) IN (5, 6) and YEAR(rd.SCROLL_DATE)= 2016;

或者,使用条件聚合(将值放在两列中:

SELECT YEAR(rd.SCROLL_DATE) as yyyy,
       SUM(CASE WHEN MONTH(rd.SCROLL_DATE) = 5 then rd.AMOUNT else 0) as total_05,
       SUM(CASE WHEN MONTH(rd.SCROLL_DATE) = 6 then rd.AMOUNT else 0) as total_06
from revenue_d rd JOIN
     revenue_m rem
     on rd.RV_ID = rem.RV_ID
Where MONTH(rd.SCROLL_DATE) IN (5, 6) and YEAR(rd.SCROLL_DATE) = 2016;

答案 2 :(得分:0)

  

UNION和UNION ALL有什么区别?

UNION删除重复的行。

UNION ALL不会删除重复的行。