求树形结构选择的SQL语句

chencane 2012-07-31 10:46:10
一个表

tb_tree(id int,treecode varchar)
/*
数据如:
id treecode
10000 0101
10010 010102
10013 010103
10022 01010204
20011 0102
20071 010203
*/


根据id来选择,如果传id=10000,根据treecode,取出其下面的所有id(10000,10010,10013),求最简单的SQL语句。

...全文
147 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Net攻城狮 2012-08-03
  • 打赏
  • 举报
回复
CREATE TABLE #aaa(
[id] [int] NULL,
[pid] [int] NULL,
[name] [nchar](10)
)
GO
INSERT INTO #aaa VALUES(1,0,'a')
INSERT INTO #aaa VALUES(2,0,'b')
INSERT INTO #aaa VALUES(3,1,'c')
INSERT INTO #aaa VALUES(4,1,'d')
INSERT INTO #aaa VALUES(5,2,'e')
INSERT INTO #aaa VALUES(6,3,'f')
INSERT INTO #aaa VALUES(7,3,'g')
INSERT INTO #aaa VALUES(8,4,'h')
GO
select * from #aaa


with my1 as(select * from #aaa where id = 1
union all select #aaa.* from my1, #aaa where my1.id = #aaa.pid
)
select * from my1



SQL递归
chencane 2012-08-02
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]

SQL code

CREATE TABLE t1
(
id INT,
treecode VARCHAR(20)
)
INSERT INTO t1
SELECT 10000, '0101' UNION ALL
SELECT 10010, '010102' UNION ALL
SELECT 10013, '010103' UNION ALL
SELE……
[/Quote]

这个比较新颖。还有其它写法吗?
gogodiy 2012-08-01
  • 打赏
  • 举报
回复

CREATE TABLE t1
(
id INT,
treecode VARCHAR(20)
)
INSERT INTO t1
SELECT 10000, '0101' UNION ALL
SELECT 10010, '010102' UNION ALL
SELECT 10013, '010103' UNION ALL
SELECT 10022, '01010204' UNION ALL
SELECT 20011, '0102' UNION ALL
SELECT 20071, '010203'
SELECT * FROM t1

SELECT a.* FROM t1 AS a INNER JOIN t1 AS b ON CHARINDEX(b.treecode,a.treecode)>0 AND b.id=10000

-------------------------------
id treecode
10000 0101
10010 010102
10013 010103
10022 01010204
chencane 2012-08-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

SQL code
select * from tb_tree
where treecode like (select treecode from tb_tree where id=2)+'%'
[/Quote]

再求。
  • 打赏
  • 举报
回复
select * from tb_tree
where treecode like (select treecode from tb_tree where id=2)+'%'
chencane 2012-07-31
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

SQL code
declare @id varchar(20)
set @id='10000'
select * from tb_tree a,
(select * from tb_tree where id=@id) b
where a.treecode like b.treecode+'%'
[/Quote]

谢谢,这个我写了的,想问下有没有更简单些的。
  • 打赏
  • 举报
回复
declare @id varchar(20)
set @id='10000'
select * from tb_tree a,
(select * from tb_tree where id=@id) b
where a.treecode like b.treecode+'%'
chencane 2012-07-31
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

感觉LZ描述的还不够详细,如id=1000,treecode为0101,它的叶节点是哪些,根据什么来取?
[/Quote]
不好意思,是我描述不清楚。
应该还要取“01010204”这条记录。

两位一个编码,根据id取此id对应编码下的treecode节点及其所有子孙节点。
  • 打赏
  • 举报
回复
感觉LZ描述的还不够详细,如id=1000,treecode为0101,它的叶节点是哪些,根据什么来取?

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧