我有以下MySQL查詢MYSQL UNION - 產生意外結果
MYSQL
SELECT SUM(shop_order_price), p.category
from shop_orders so
INNER JOIN product p
on so.shop_order_product_id=p.product_id
WHERE so.shop_order_action = 'Sale'
AND so.brand = '53'
AND p.category = 'Mens'
AND so.shop_order_location = 'Bawtry'
AND so.shop_order_month = '05' AND so.shop_order_year = '2014'
UNION ALL
SELECT SUM(shop_order_price), p.category
from shop_orders so
INNER JOIN product p
on so.shop_order_product_id=p.product_id
WHERE so.shop_order_action = 'Sale'
AND so.brand = '53'
AND p.category= 'Ladies'
AND so.shop_order_location = 'Bawtry'
AND so.shop_order_month = '05' AND so.shop_order_year = '2014'
UNION ALL
SELECT SUM(shop_order_price), p.category
from shop_orders so
INNER JOIN product p
on so.shop_order_product_id=p.product_id
WHERE so.shop_order_action = 'Sale'
AND so.brand = '53'
AND so.shop_order_location = 'Bawtry'
AND so.shop_order_month = '05' AND so.shop_order_year = '2014'
將會產生以下結果:
結果
SUM(shop_order_price) category
-------------------- ---------
282.5 Mens
751 Ladies
1033.5 Ladies
SUM數字是正確的,但是,底部的行在類別列中顯示'Ladies',即使在查詢中沒有指定類別。
我的問題是我可以得到這最後一行顯示TOTAL
,而不是Ladies
?所以如下結果會出現:
預期結果
SUM(shop_order_price) category
-------------------- ---------
282.5 Mens
751 Ladies
1033.5 TOTAL
任何意見將是巨大的。
這是更加優化 - 謝謝。無論如何要在最後一行顯示'TOTAL'而不是_NULL_? – aphextwix 2014-09-02 13:20:07
你可以把查詢放在派生表中,我會更新。 – 2014-09-02 13:33:00
感謝您的更新答案 - 您是否介意解釋爲什麼您不會使用它的原因? – aphextwix 2014-09-02 13:48:24