国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

MySQL中union和join語句使用區別的辨析教程

2024-07-24 12:45:16
字體:
來源:轉載
供稿:網友

union和join是需要聯合多張表時常見的關聯詞,具體概念我就不說了,想知道上網查就行,因為我也記不準確。
先說差別:union對兩張表的操作是合并數據條數,等于是縱向的,要求是兩張表字段必須是相同的(Schema of both sides of union should match.)。也就是說如果A表中有三條數據,B表中有兩條數據,那么A union B就會有五條數據。說明一下union 和union all的差別,對于union如果存在相同的數據記錄會被合并,而union all不會合并相同的數據記錄,該有多少條記錄就會有多少條記錄。例如在mysql下執行以下語句:

select * from tmp_libingxue_a;name numberlibingxue 1001yuwen 1002select * from tmp_libingxue_b;name numberlibingxue 1001feiyao 1003select * from tmp_libingxue_a union select * from tmp_libingxue_b;libingxue 1001yuwen 1002feiyao 1003select * from tmp_libingxue_a union all select * from tmp_libingxue_b;libingxue 1001yuwen 1002libingxue 1001feiyao 1003

但是這樣在hive里面是不能執行的,執行select * from tmp_libingxue_a union all select * from tmp_libingxue_b;會failed,hive中union必須在子查詢中進行。如

select * from (select * from tmp_yuwen_a union all select * from tmp_yuwen_b) t1;

注意,必須是union all,單獨用union它會提示你缺少ALL,而且后面的t1必須寫,你可以寫成a或者b,但是一定要寫,不寫會出錯。
而join則是偏于橫向的聯合,僅僅是偏向于,等下詳細說明。join跟union比起來顯得更寬松,對兩個表的字段不做要求,沒有限制條件的join等于兩個表的笛卡爾乘積,所有join需要有限制條件來約束,經過限制的join就是橫向的擴張了。對于滿足限制條件的join會被提取出來,不滿足的直接過濾掉。用法可以很靈活,下面有兩個簡單的例子:

select * from (select * from tmp_yuwen_a)t1 join (select * from tmp_yuwen_b) t2;select * from tmp_yuwen_a t1 join (select * from tmp_yuwen_b) t2;

left outer join和right outer join用法類似,區別就是left outer join會把左邊表的字段全部選擇出來,右邊表的字段把符合條件的也選擇出來,不滿足的全部置空,也就是說以左邊表為參照。right outer join同理以右邊表為參照。這三個join之間的差別說過很多次,網上也有更詳細的解釋,不再贅述。
相同點:在某些特定的情況下,可以用join實現union all的功能,這種情況是有條件的,當出現這種情況的時候選擇union all還是group by就可以看情況或者看兩者的消耗而決定。sql雖然就在那么幾個關鍵詞,但變化多端、功能強大,只要能實現想要的功能,怎么用隨便你。需求情況sql簡單重現如下

drop table tmp_libingxue_resource;create external table if not exists tmp_libingxue_resource( user_id string, shop_id string, auction_id string, search_time string)partitioned by (pt string)row format delimited fields terminated by '/t'lines terminated by '/n'stored as sequencefile;drop table tmp_libingxue_result;create external table if not exists tmp_libingxue_result( user_id string, shop_id string, auction_id string, search_time string)partitioned by (pt string)row format delimited fields terminated by '/t'lines terminated by '/n'stored as sequencefile;insert overwrite table tmp_libingxue_result where(pt=20041104) select * from tmp_libingxue_resource;
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新邵县| 昭苏县| 丹凤县| 寿光市| 甘孜| 西充县| 佛学| 沭阳县| 内丘县| 舟山市| 梓潼县| 澄江县| 平安县| 团风县| 茂名市| 南雄市| 永顺县| 成安县| 大渡口区| 广南县| 保亭| 黔江区| 灵武市| 本溪市| 安阳县| 石泉县| 民乐县| 漳平市| 临汾市| 威宁| 凤山市| 且末县| 安乡县| 孟州市| 呼和浩特市| 天峻县| 呼图壁县| 炎陵县| 白玉县| 平罗县| 亚东县|