mysql union all 區分表名稱

背景:

最近在做報表統計,因爲查不同的訂單分佈在不同的表裏面,不同的表訂單狀態也不一樣,所以用union all 做連接的時候要區分數據是來自那張表的。

(SELECT EMAIL,sum(BESTELLWERT) as user_amount,count(*) as user_order_count,
'order' as order_table  from `order`.`order` WHERE `status` = 4 AND STAMP 
BETWEEN '2016-01-01' AND '2019-05-31' GROUP BY EMAIL HAVING SUM(BESTELLWERT) 
between 4000 and 5000)
union all
(SELECT EMAIL,sum(BESTELLWERT) as user_amount,count(*) as user_order_count,
'cdkey_order' as order_table  from `order`.`cdkey_order` WHERE `status` = 2 AND 
STAMP BETWEEN '2016-01-01' AND '2019-05-31' GROUP BY EMAIL HAVING SUM(BESTELLWERT) 
between 4000 and 5000)
union all
(SELECT EMAIL,sum(BESTELLWERT) as user_amount,count(*) as user_order_count,
'lvlguide_order' as order_table  from `order`.`lvlguide_order` WHERE `status` = 4
 AND STAMP BETWEEN '2016-01-01' AND '2019-05-31' GROUP BY EMAIL HAVING 
SUM(BESTELLWERT) between 4000 and 5000)

例子:union all 數據表來源order表則在select 字段時候增加:'order' as order_table from xxxx 那麼這個字段就可以標記來源那張表

同理:union all數據表來自cdk表,則在select時候增加:'cdkey' as order_table from xxxx

再來個例子:

(select name,uid,'user' as table_name from user)

   union all

(select name,uid,'customer' as table_name from customer)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章