本文介绍CTE的使用方法。

CTE用于WITH子句定义一个子查询关系,可供SELECT查询引用。

以下两个查询是等价的:

SELECT a, b
FROM (SELECT a, MAX(b) AS b FROM t GROUP BY a) AS x;
WITH x AS (SELECT a, MAX(b) AS b FROM t GROUP BY a)
SELECT a, b FROM x;

WITH子句同样适用于多子查询:

WITH
t1 AS (SELECT a, MAX(b) AS b FROM x GROUP BY a),
t2 AS (SELECT a, AVG(d) AS d FROM y GROUP BY a)
SELECT t1.*, t2.*
FROM t1 JOIN t2 ON t1.a = t2.a;

WITH子句中定义的关系可以互相连接:

WITH
x AS (SELECT a FROM t),
y AS (SELECT a AS b FROM x),
z AS (SELECT b AS c FROM y)
SELECT c FROM z;
  • CTE后面必须直接跟使用CTE的SQL语句(如SELECT、INSERT、UPDATE等),否则CTE将失效。
  • CTE后面也可以跟其他的CTE,但只能使用一个WITH,多个CTE中间用逗号(,)分隔。
  • CTE语句里暂时不支持分页。