公用表表达式和派生表类似的另一种形式的表表达式,CTE中是先定义表,然后再引用,结构比较清晰
CTE相比派生表的优势:如果有多个子查询,不需要像派生表那样嵌套,只需要在WITH中定义多个CTE,每个CTE可以引用它前面定义的所有CTE
派生表:from子句中的子查询。
select * from (select 1,2,3) tb(c1,c2,c3) --c1、c2、c3是列别名
CTE:
with
tb(c1,c2,c3) as (select 1,2,3) select * from tb
多个CTE:
with tb1(c1,c2,c3) as (select 1,2,3), tb2(c1,c2,c3) as (select * from tb1) select * from tb2
多个相同的派生表使用一个CTE就可以:
--派生表相同,重复写了两遍
SELECT tb1.years,tb1.ordercount 当年订单数,tb2.ordercount 上年订单数,tb1.ordercount-tb2.ordercount 差额 FROM (SELECT YEAR( AddTime) years,COUNT(ID) ordercount FROM TB_Order GROUP BY YEAR(AddTime)) tb1 join (SELECT YEAR(AddTime) years,COUNT(ID) ordercount FROM TB_Order GROUP BY YEAR(AddTime)) tb2 on tb1.years=tb2.years+1
--只需要写一个CTE,可重用
WITH tb AS (SELECT YEAR( AddTime) years,COUNT(ID) ordercount FROM TB_Order GROUP BY YEAR(AddTime)) SELECT tb1.years,tb1.ordercount 当年订单数,tb2.ordercount 上年订单数,tb1.ordercount-tb2.ordercount 差额 FROM tb AS tb1 join tb AS tb2 on tb1.years=tb2.years+1
递归CTE:
比如有一个类目表,类目有上下级关系,给定一个类目如何查出所有下级类目?这时候可以使用递归CTE实现此功能
WITH leimu AS ( --起点,仅执行一次 SELECT ID,Name,ParentID FROM TLZ_LEIMU WHERE parentid=0 UNION ALL --合并 --递归查询,可能多次执行,直到查询结果为空 SELECT ID,Name,ParentID FROM TLZ_LEIMU c INNER JOIN leimu p WHERE c.parentid=p.id ) SELECT * FROM leimu
未完待续