SQL 列不同的表查询结果合并操作

2022-07-29,,,

两个不同的表进行查询,需要把结果合并

比如table1的列为 id, user_id, type_id,pro_id;

table2的列为 id,user_id,collect_id;分别如下图所示

table1:

table2:

将两个表的查询结果合并到一起的查询语句为

select *, null as collect_id from table1 where user_id = 527
union
select id,user_id,null as type_id,null as pro_id, collect_id from table2 where user_id = 527;

结果为:

其实就是把对应的列补充到没有该列的表中,在例子中就是把collect_id补充到table1中,

把type_id,pro_id补充到table2中。

补充知识:sql结果集合并用union all 不同表的列合并用join

结果集合并用union all 不同表的列合并用join

select
"模块名",
"事件编码",
"点击数量",
"使用时长(单位:分)"
from

(select 
t.fun_name as "模块名",
t.event_code as "事件编码",
sum(click_records) as "点击数量"
from 
(select m.* from default.daily_new_clientrpt_master m where event_id in ( select max(event_id) as "事件" from default.daily_new_clientrpt_master group by user_name,fun_code order by "事件" desc ) ) t where day = today() group by "模块名" ,"事件编码") t5
join
(
select 
t.fun_name as "模块名",
t.event_code as "事件编码",
round(sum(stay_time)/60000,0) as "使用时长(单位:分)"
from 
(select m.* from default.daily_new_clientrpt_master m where event_id in 
 ( 
 select "事件" from (
 select max(event_id) as "事件", max(stay_time) as "事件1" from default.daily_new_clientrpt_master group by user_name,fun_code order by "事件1" desc) )
) 
 t where day = today() and like(event_code,'%10000') group by "模块名" ,"事件编码"
) t6 on t5."模块名"=t6."模块名" and t5."事件编码"=t6."事件编码"

以上这篇sql 列不同的表查询结果合并操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《SQL 列不同的表查询结果合并操作.doc》

下载本文的Word格式文档,以方便收藏与打印。