日期:2014-05-17  浏览次数:20554 次

求树形结构选择的SQL语句
一个表 
SQL code

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语句。



------解决方案--------------------
感觉LZ描述的还不够详细,如id=1000,treecode为0101,它的叶节点是哪些,根据什么来取?
------解决方案--------------------
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+'%'

------解决方案--------------------
SQL code
select * from tb_tree
where treecode like (select treecode from tb_tree where id=2)+'%'

------解决方案--------------------
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
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