MySQL UNION似乎无法正常工作

时间:2016-04-01 13:16:30

标签: mysql union union-all

我有一个SQL查询,用于从订单数据库中提取数据。我正在查询2个表并使用UNION ALL组合结果。但是,UNION ALL似乎没有按预期工作。这是我正在使用的查询:

SELECT year(oc_order.date_added) AS year, COUNT(oc_order.order_id) as cnt, SUM( ifnull(oc_order.new_total,oc_order.total) ) as total
FROM oc_order
WHERE oc_order.order_status_id IN (1,3,5)
    AND MONTH(oc_order.date_added) BETWEEN '01' AND '02'
    AND DAY(oc_order.date_added) BETWEEN '01' AND '31'
GROUP BY year(oc_order.date_added)

UNION ALL

SELECT ifnull(year(str_to_date(oc_return_custom.date_added,'%d-%m-%Y %H:%i:%s')),year(str_to_date(oc_return_custom.date_added,'%Y-%m-%d %H:%i:%s')) ) AS year, COUNT(oc_return_custom.return_id) as cnt, SUM( oc_return_custom.total ) as total
FROM oc_return_custom
WHERE ifnull(MONTH(str_to_date(oc_return_custom.date_added,'%d-%m-%Y %H:%i:%s')),MONTH(str_to_date(oc_return_custom.date_added,'%Y-%m-%d %H:%i:%s')) ) BETWEEN '01' AND '02'
    AND ifnull(DAY(str_to_date(oc_return_custom.date_added,'%d-%m-%Y %H:%i:%s')),DAY(str_to_date(oc_return_custom.date_added,'%Y-%m-%d %H:%i:%s')) ) BETWEEN '01' AND '31'
GROUP BY ifnull(year(str_to_date(oc_return_custom.date_added,'%d-%m-%Y %H:%i:%s')),year(str_to_date(oc_return_custom.date_added,'%Y-%m-%d %H:%i:%s')) )
ORDER BY year DESC

这是我从查询中获得的:

+=======+========+=======+
| year  | cnt    | total |
+=======+========+=======+
| 2016  |  200   |  1000 |
| 2016  |   50   |   200 |
| 2015  |  100   |   800 |
| 2015  |   10   |    50 |
+=======+========+=======+

但这是我想要的:

+=======+========+=======+
| year  | cnt    | total |
+=======+========+=======+
| 2016  |  250   |  1200 |
| 2015  |  110   |   850 |
+=======+========+=======+

有人能告诉我我做错了吗?

注意: oc_order表的date_added列是datetime,而oc_return_custom的date_added列只是文本。

1 个答案:

答案 0 :(得分:2)

UNION ALL只是将单独的 GROUP BY操作生成的两个数据集放在一起。

要获得预期的结果集,您必须将查询包装在子查询中并应用其他GROUP BY

SELECT year, SUM(cnt) AS cnt, SUM(total) AS total
FROM ( ... your query here ...) AS t
GROUP BY year