SQL 列不同的表查询结果合并操作
时间:2021-03-04 13:51:43|栏目:Mysql|点击: 次
两个不同的表进行查询,需要把结果合并,
比如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."事件编码"
上一篇:mysql数据库应付大流量网站的的3种架构扩展方式介绍
栏 目:Mysql
下一篇:阿里云centos7中安装MySQL8.0.13的方法步骤
本文标题:SQL 列不同的表查询结果合并操作
本文地址:http://www.codeinn.net/misctech/73954.html