求教递归删除的SQL
表结构如下:
tableName:test
id pid name
1 null 1
2 1 2
3 1 3
4 3 4
输入参数为id数组,期望结果为删除该id数组中各个id及其子节点的记录
如:
id in (2,3)
则删除后结果为
id pid name
1 null 1
id in (1,3)
则删除后结果为
id pid name
(完全删除)
注:
持久层框架为Mybatis,若能用Mybatis的XML文件亦可。
另:
求教WITH a AS(SELECT * FROM test),在MySql中是否有效。若有效正确写法是什么?
[解决办法]
可以参考下贴中的递归实现思路。
http://blog.csdn.net/acmain_chm/article/details/4142971
MySQL中进行树状所有子节点的查询
在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点。但很遗憾,在MySQL的目前版本中还没有对应的功能。 在MySQL中如果是有限的层次,比如我们事先如果可以确定这个树的最大深度是4, 那么所有节点为根的树的深度均不会超过4,则我们可以直接通过left join 来实现。 但很多时候我们...
[解决办法]
这个是Server SQL 中的写法,可以参考一下
- SQL code
--测试数据DECLARE @tb Table([id] int,[col1] varchar(8),[col2] int)insert @tbselect 1,'河北省',0 union allselect 2,'邢台市',1 union allselect 3,'石家庄市',1 union allselect 4,'张家口市',1 union allselect 5,'南宫',2 union allselect 6,'坝上',4 union allselect 7,'任县',2 union allselect 8,'清河',2 union allselect 9,'河南省',0 union allselect 10,'新乡市',9 --删除河南北省及以下所有节点;with t as(select * from @tb where id IN(1)union allselect a.* from @tb a ,t where a.col2=t.id)DELETE TB FROM @tb TB WHERE TB.id IN( SELECT t.id FROM t)SELECT * FROM @tb/*(10 行受影响)(8 行受影响)id col1 col2----------- -------- -----------9 河南省 010 新乡市 9(2 行受影响)*/