SparkSQL视图

Spark视图分类

视图是基于真实表的一张虚拟的表,其数据来源均建立在真实表的基础

视图提供的是对查询操作的封装,本身不包含数据,所呈现的数据是根据视图定义从基础表中检索出来的,如果基础表的数据新增或删除,视图呈现的也是更新后的数据。视图定义后,编写完所需的查询,可以方便地重用该视图

临时视图(temporary view)

临时视图只适用于SparkSQL,无法在MySQL和Hive中使用

  • 只在当前会话【有效】,如果会话结束,则临时视图【消失】
  • 支持重新覆盖
  • 缓存表也属于临时视图,可以在spark监控页面中的Storage查看

永久视图(view)

  • 保存一段查询语句的【过程逻辑】,而不是查询语句的【结果】
  • 永久有效,查询这个视图,相当于查询【原select 语句】,如果保存的查询逻辑复杂,这查询视图也耗时
  • 支持重新覆盖

案例代码

-- 临时视图
create temporary view tmp_view(name,age) as values ('Jack',19);
-- 支持重新覆盖
create or replace temporary view or_replace_tmp_view(name,age) as values ('Jack',19);

-- 缓存表
--cache语法在pycharm中会红色警告,不用理会,选中运行即可
cache table cache_table as select * from tmp_view;

-- 永久视图
create view view1(name,age) as values ('Jack',19);
-- 支持重新覆盖
create or replace view view2(name,age) as values ('Jack',19);

--查看所有的视图(没法看表)
show views;
--查看所有的表,也会显示视图
show tables;

应用

拓展横向迭代计算的5种方法

已知c1字段,计算c2和c3字段

c1 c2=c1+2 c3=c1*c2
1
2
3
drop view if exists test1;
--快速创建数据集
create or replace temporary view test1(c1) as values (1),(2),(3);

--方式一、用子查询的方式
select c1,
       c2,
       c1 * c2 as c3
from (select c1,c1 + 2 as c2 from test1);

--方式二、用with as
with tmp as (select c1,c1 + 2 as c2 from test1)
select c1,
       c2,
       c1 * c2 as c3
from tmp;

--方式三、用永久视图view
create or replace view view1 as select c1, c1 + 2 as c2 from test1;
create or replace view view2 as select c1,c2,c1*c2 as c3 from view1;

--方式四、用临时视图temporary view
create or replace temporary view temp_view1 as select c1, c1 + 2 as c2 from test1;
create or replace temporary view temp_view2 as select c1, c1 + 2 as c2 from temp_view1;

--方式五、用缓存表cache table
cache table cache_table1 as select c1,c1+2 as c2 from test1;
cache table cache_table2 as select c1,c2,c1*c2 as c3  from cache_table1;

select * from view2;
+------+-----+------+
|  c1  |  c2  |  c3  |
+------+------+------+
|  1   |  3   |  3   |
|  2   |  4   |  8   | 
|  3   |  5   |  15  |
+------+------+------+

你可能感兴趣的:(Spark,spark,大数据,分布式)