时间:2021-07-01 10:21:17 帮助过:43人阅读
-- 以下代码使用SQLite 3.18.0 测试通过 WITH [depts]([dept_id]) AS( SELECT [d].[dept_id] FROM [dept] [d] JOIN [employees] [e] ON [d].[dept_id] = [e].[dept_id] WHERE [e].[emp_name] = ‘西北-经理‘ UNION ALL SELECT [d].[dept_id] FROM [dept] [d] JOIN [depts] [s] ON [d].[parent_id] = [s].[dept_id] ) SELECT * FROM [employees] WHERE [dept_id] IN (SELECT [dept_id] FROM [depts]);
可能有些同学对CTE(Common Table Expression)还不太熟悉,这里简单说一下,有兴趣的同学可以google或者百度,介绍很多(这里以SQLite举例):
我还是更喜欢称CTE(Common Table Expression)为“公用表变量”而不是“公用表达式”,因为从行为和使用场景上讲,CTE更多的时候是产生(分迭代或者不迭代)结果集,供其后的语句使用(查询、插入、删除或更新),如上述的例子就是一个典型的利用迭代遍历树形结构数据。
CTE的优点:
为了更好的说明CTE的能力,这里附上两个例子(转自SQLite官网文档)
曼德勃罗集合(Mandelbrot set)
-- 以下代码使用SQLite 3.18.0 测试通过 WITH RECURSIVE xaxis(x) AS (VALUES(-2.0) UNION ALL SELECT x+0.05 FROM xaxis WHERE x<1.2), yaxis(y) AS (VALUES(-1.0) UNION ALL SELECT y+0.1 FROM yaxis WHERE y<1.0), m(iter, cx, cy, x, y) AS ( SELECT 0, x, y, 0.0, 0.0 FROM xaxis, yaxis UNION ALL SELECT iter+1, cx, cy, x*x-y*y + cx, 2.0*x*y + cy FROM m WHERE (x*x + y*y) < 4.0 AND iter<28 ), m2(iter, cx, cy) AS ( SELECT max(iter), cx, cy FROM m GROUP BY cx, cy ), a(t) AS ( SELECT group_concat( substr(‘ .+*#‘, 1+min(iter/7,4), 1), ‘‘) FROM m2 GROUP BY cy ) SELECT group_concat(rtrim(t),x‘0a‘) FROM a;
运行后的结果,如下图:(使用SQLite Expert Personal 4.2 x64)
数独问题(Sudoku)
假设有类似下图的问题:
-- 以下代码使用SQLite 3.18.0 测试通过 WITH RECURSIVE input(sud) AS ( VALUES(‘53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79‘) ), digits(z, lp) AS ( VALUES(‘1‘, 1) UNION ALL SELECT CAST(lp+1 AS TEXT), lp+1 FROM digits WHERE lp<9 ), x(s, ind) AS ( SELECT sud, instr(sud, ‘.‘) FROM input UNION ALL SELECT substr(s, 1, ind-1) || z || substr(s, ind+1), instr( substr(s, 1, ind-1) || z || substr(s, ind+1), ‘.‘ ) FROM x, digits AS z WHERE ind>0 AND NOT EXISTS ( SELECT 1 FROM digits AS lp WHERE z.z = substr(s, ((ind-1)/9)*9 + lp, 1) OR z.z = substr(s, ((ind-1)%9) + (lp-1)*9 + 1, 1) OR z.z = substr(s, (((ind-1)/3) % 3) * 3 + ((ind-1)/27) * 27 + lp + ((lp-1) / 3) * 6, 1) ) ) SELECT s FROM x WHERE ind=0;
一句SQL完成动态分级查询
标签:bar 需要 模板 pre 而不是 2.0 sts 通过 name