sql树形查询
sql:
使用Common As:递归公用表
sql:http://blog.51cto.com/tianxingzhe/1720092
/****** Script for SelectTopNRows command from SSMS ******/ --查询某个节点上的所有父节点 如果需要过滤在where后面跟过滤条件 WITH MyTest AS ( --起始条件 SELECT id, title, parent FROM tb_menu WHERE id = 44 --列出子节点查询条件 UNION ALL --http://www.w3school.com.cn/sql/sql_union.asp --递归条件 SELECT a.id, a.title, a.parent FROM tb_menu a INNER JOIN MyTest b --执行递归,这里就要理解下了 ON a.id = b.parent) SELECT * FROM MyTest;
--查询父节点下面的子节点 WITH cte_child (id, title, parent, level) AS ( --起始条件 SELECT id, title, parent, 0 AS level FROM tb_menu WHERE id = 6 --列出父节点查询条件 UNION ALL --递归条件 SELECT a.id, a.title, a.parent, b.level + 1 FROM tb_menu a INNER JOIN cte_child b ON (a.parent = b.id)) SELECT * FROM cte_child;
Oracle的树形:
Oracle:https://blog.csdn.net/u014421556/article/details/51689787
Oracle树查询的最重要的就是select...start with... connect by...prior语法了。
--列出父节点的所有子节点<font></font> SELECT *<font></font> FROM VD_REGIONAL vr START WITH ID = '0358DEF3091E6E9AE0503F0A05020A18' CONNECT BY vr.PARENT_ID = PRIOR vr.ID;
--列出子节点的所有父节点 不要顶级父类 [WHERE vr.PARENT_ID!='0']<font></font> SELECT * FROM VD_REGIONAL vr START WITH ID = '2c90898b63f968f40163fc31b37c08d3' CONNECT BY vr.ID = PRIOR vr.PARENT_ID; --条件筛选 SELECT * FROM VD_REGIONAL vr WHERE vr.PARENT_ID!='0' START WITH ID = '2c90898b63f968f40163fc31b37c08d3' CONNECT BY vr.ID = PRIOR vr.PARENT_ID;