0
我有一個SQL查詢,我用來從訂單數據庫中提取數據。我在查詢2個表格,並使用UNION ALL結合結果。但是,UNION ALL似乎沒有按預期工作。下面是我使用的查詢:MySQL UNION似乎沒有正常工作
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列只是文本。
我準備好,UNION的文件大概3次,我只是沒有意識到這一點。我嘗試使用子查詢,但我想我做錯了什麼! Ευχαριστώ! –