Spark DataFrame中的join使用说明

spark sql 中join的类型

Spark DataFrame中join与SQL很像,都有inner join, left join, right join, full join;

类型 说明
inner join 内连接
left join 左连接
right join 右连接
full join 全连接

 spark join 看其原型

def join(right : DataFrame, usingColumns : Seq[String], joinType : String) : DataFrame 
def join(right : DataFrame, joinExprs : Column, joinType : String) : DataFrame 

joinType可以是”inner”、“left”、“right”、“full”分别对应inner join, left join, right join, full join,默认值是”inner”,代表内连接

例子:  

 a表

id job
1 张3
2 李四
3 王武

b表   

id job parent_id
1 23 1
2 34 2
3 34 4

内连接

内连接:内连接查询操作列出与连接条件匹配的数据行,它使用比较运算符比较被连接列的列值。

df.join(df, Seq("city", "state"), "inner").show
df.join(df, Seq("city", "state")).show

 Seq是指连接的字段,这个相当于

 SELECT   a.au_fname,   a.au_lname,   p.pub_name   
   FROM   authors   AS   a   INNER   JOIN   publishers   AS   p   
        ON   a.city   =   p.city   
        AND   a.state   =   p.state   
  ORDER   BY   a.au_lname   ASC,   a.au_fname   ASC   

结果是     

  1   张三               1     23     1   
  2   李四                  2     34     2 

左外连接

左联接:是以左表为基准,将a.stuid = b.stuid的数据进行连接,然后将左表没有的对应项显示,右表的列为NULL

df.join(df, Seq("city", "state"), "left").show

 结果是

  1   张三                  1     23     1   
  2   李四                  2     34     2   
  3   王武                  null  null null 

 

 

 



 

猜你喜欢

转载自www.cnblogs.com/yyy-blog/p/10249298.html
今日推荐