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)

 

 

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