MySQL中union和join语句使用区别的辨析教程

2019-01-04 17:58:16王旭
sudo -u taobao hadoop dfs -rmr /group/tbads/warehouse/tmp_libingxue_result/pt=20041104 sudo -u taobao hadoop jar /home/taobao/dataqa/framework/DailyReport.jar com.alimama.loganalyzer.tool.SeqFileLoader tmp_libingxue_resource.txt hdfs://v039182.sqa.cm4:54310/group/tbads/warehouse/tmp_libingxue_result/pt=20041104/part-00000
hive> select * from tmp_libingxue_resource;
OK 2001 0 11 101 20041104 2002 0 11 102 20041104
hive> select * from tmp_libingxue_result;
OK 2001 0 12 103 20041104 2002 0 12 104 20041104
select user_id,shop_id,max(auction_id),max(search_time) from (select * from tmp_libingxue_resource union all select * from tmp_libingxue_result )t1 group by user_id,shop_id;
2001 0 12 103 2002 0 12 104
select t1.user_id,t1.shop_id,t2.auction_id,t2.search_time from (select * from tmp_libingxue_resource) t1 join (select * from tmp_libingxue_result) t2 on t1.user_id=t2.user_id and t1.shop_id=t2.shop_id;


通过前面的介绍,使用UNION对表的结果集进行并运算与使用JOIN对多表进行连接,二者有本质的不同。
下面给出一个使用UNION运算符连接二表记录的运算实例。
典型的二表记录的UNION运算
2001 0 12 103 2002 0 12 104

假定有两个表Table3和Table4,其包含的列和数据分别如下所示。

Table1数据库表

20151216110017983.png (591×135)

Table2数据库表

20151216110102452.png (582×131)

Table1表和Table2表具有相同的列结构,因此可以使用UNION运算符连接两个表的记录集,得到的连接结果如下表所示。

使用UNION连接Table3表和Table4表的记录

20151216110125850.png (589×272)

上述连接过程的实现代码可表示如下:

SELECT * FROM Table1 UNION SELECT * FROM Table2

您可能感兴趣的文章:

MySQL在右表数据不唯一的情况下使用left join的方法在MySQL中使用STRAIGHT_JOIN的教程在MySQL中使用JOIN语句进行连接操作的详细教程MySQL中视图的使用及多表INNER JOIN的技巧分享MYSQL使用inner join 进行 查询/删除/修改示例解析mysql left( right ) join使用on与where筛选的差异深入理解mysql之left join 使用详解Mysql中Join的使用实例详解