文章目录
一. 定义
with A as (select * from class)
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>
官网文档:
//去除 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;
}