自己總結sql用法

**

- 2018/12/05 with as 用法

**

一、hivesql中(注意:mysql不支持),with as語句的作用是相當於創建了一箇中間表,加載到內存中,這樣在後續的使用中極大的提高速度(不用建表,insert數據到中間表;加載內存,使用數據速度快)。
二、使用
WITH t1 AS (
SELECT *
FROM carinfo
),
t2 AS (
SELECT *
FROM car_blacklist
)
SELECT *
FROM t1, t2

注意:這裏必須要整體作爲一條sql查詢,即with as語句後不能加分號,不然會報錯。

三、注意事項

  1. with子句必須在引用的select語句之前定義,同級with關鍵字只能使用一次,多個只能用逗號分割;最後一個with 子句與下面的查詢之間不能有逗號,只通過右括號分割,with 子句的查詢必須用括號括起來.

以下寫法會報錯:

with t1 as (select * from carinfo)
with t2 as (select * from car_blacklist)
select * from t1,t2
1
2
3
with t1 as (select * from carinfo);
select * from t1
1
2
2.如果定義了with子句,但其後沒有跟select查詢,則會報錯!

以下寫法會報錯:

with t1 as (select * from carinfo)
1
正確寫法(沒有使用 t1沒關係,其後有select就行):

with t1 as (select * from carinfo)
select * from carinfo
1
2
3.前面的with子句定義的查詢在後面的with子句中可以使用。但是一個with子句內部不能嵌套with子句!

正確寫法:

with t1 as (select * from carinfo),
t2 as (select t1.id from t1)
select * from t2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章