个人觉得这个SQL语句不错,可以总结下来,待以后使用
一.用with 可以查询数据库的关联节点。
1.数据库表:
id name parentId
1 | 公司 | 0 |
2 | 张一 | 1 |
3 | 李一 | 1 |
4 | 张二 | 2 |
5 | 张三 | 2 |
6 | 张四 | 4 |
7 | 张五 | 6 |
NULL | NULL | NULL |
2.SQL语句:
with cr(username,userid)
as(
select a.username,a.userid from userTB a where parentId='2'
union all
select c.username,c.userid from userTB c
inner join cr on c.parentId=cr.userid
)
select * from cr
3.对上述SQL的解释
cr:表示一个临时表名
4.语法:
with 临时表名 as :可以定义一个SQL片段,该片段可以被整个语句用到,特别是对于union all特别有用,可以提供一部分数据,因为union all的每个部分都一样,则每个部门如果都去执行一遍的,所以可以使用他只执行一遍,如果with的表被执行大于两次时,会将此表保存成一个临时表,否则不会,这样会大大提高效率
5.注意事项:
with as(CTE)属于sql server2005及以上版本才拥有的功能,如果在sql server 2000上执行,会提示错误“WITH附近有语法错误”。