SQL 列不同的表查詢結果合并操作
兩個不同的表進行查詢,需要把結果合并,
比如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;
結果為:
其實就是把對應的列補充到?jīng)]有該列的表中,在例子中就是把collect_id補充到table1中,
把type_id,pro_id補充到table2中。
補充知識:sql結果集合并用union all 不同表的列合并用join
結果集合并用union all 不同表的列合并用join
SELECT "模塊名", "事件編碼", "點擊數(shù)量", "使用時長(單位:分)" FROM (SELECT T.fun_name as "模塊名", T.event_code as "事件編碼", SUM(click_records) as "點擊數(shù)量" 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 列不同的表查詢結果合并操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Mysql中count(*)、count(1)、count(主鍵id)與count(字段)的區(qū)別
本文主要介紹了Mysql中count(*)、count(1)、count(主鍵id)與count(字段)的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07mysql中循環(huán)截取用戶信息并插入到目標表對應的字段中
將各個用戶對應的屬性插入到目標表對應的字段中,last_update為數(shù)據(jù)更新日期2014-08-08