兩個(gè)不同的表進(jìn)行查詢,需要把結(jié)果合并,
比如table1的列為 id, user_id, type_id,pro_id;
table2的列為 id,user_id,collect_id;分別如下圖所示
table1:
![](/d/20211017/d56fe9e655f007097294096549ed4d42.gif)
table2:
![](/d/20211017/ffc2538b194d5a1a62e173d571fc6221.gif)
將兩個(gè)表的查詢結(jié)果合并到一起的查詢語(yǔ)句為
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;
結(jié)果為:
![](/d/20211017/11921ab6726bbbd3d46ef50f81445699.gif)
其實(shí)就是把對(duì)應(yīng)的列補(bǔ)充到?jīng)]有該列的表中,在例子中就是把collect_id補(bǔ)充到table1中,
把type_id,pro_id補(bǔ)充到table2中。
補(bǔ)充知識(shí):sql結(jié)果集合并用union all 不同表的列合并用join
結(jié)果集合并用union all 不同表的列合并用join
SELECT
"模塊名",
"事件編碼",
"點(diǎn)擊數(shù)量",
"使用時(shí)長(zhǎng)(單位:分)"
FROM
(SELECT
T.fun_name as "模塊名",
T.event_code as "事件編碼",
SUM(click_records) as "點(diǎn)擊數(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 "使用時(shí)長(zhǎng)(單位:分)"
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 列不同的表查詢結(jié)果合并操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Mysql兩表聯(lián)合查詢的四種情況總結(jié)
- 解決sql server保存對(duì)象字符串轉(zhuǎn)換成uniqueidentifier失敗的問(wèn)題
- SQL server 自增ID--序號(hào)自動(dòng)增加的字段操作
- SQL Server中identity(自增)的用法詳解
- MySQL5.7.31 64位免安裝版使用教程圖解
- SqlServer生成連續(xù)數(shù)字根據(jù)指定的數(shù)字操作