文章目錄
- 一. 定義
- 二. 用法
- 三. 解析
一. 定義
with A as (select * from class)
也就是將重復用到的大批量 的SQL語句,放到with as 中,加一個別名,在后面用到的時候就可以直接用。對于大批量的SQL數據,起到優化的作用。
with子句的返回結果存到用戶的臨時表空間中,只做一次查詢,反復使用
,提高效率。
?
二. 用法
- with子句只能被select查詢塊引用
- 在同級select前有多個查詢定義的時候,第1個用with,后面的不用with,并且用逗號隔開。
- 最后一個with 子句與下面的查詢之間不能有逗號,只通過右括號分割,with 子句的查詢必須用括號括起來。
-- 針對一個別名
-- –相當于建了個e臨時表with e as (select * from scott.emp e where e.empno=7499)
select * from e;-- –針對多個別名,相當于建了e、d臨時表with
e as (select * from scott.emp),
d as (select * from scott.dept)
select * from e, d where e.deptno = d.deptno;
?
三. 解析
<dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>4.9</version>
</dependency>
官網文檔:
https://jsqlparser.github.io/JSqlParser/usage.html#parse-a-sql-statements
//去除 with語法下的別名
private static Set<String> removeWithAlias(String sql, Set<String> tables) { if (sql.contains("with ")) { PlainSelect select = null; try { select = (PlainSelect) CCJSqlParserUtil.parse(sql); List<WithItem> withItemsList = select.getWithItemsList(); List<String> withAlias = withItemsList.stream() .map(withItem -> withItem.getAlias().getName()) .collect(Collectors.toList()); return tables.stream().filter(t -> !withAlias.contains(t)) .collect(Collectors.toSet()); } catch (Exception e) { e.printStackTrace(); } } return tables;
}
?