一般比较普遍的就是四种方法:(具体见 SQL Anti-patterns这本书)
金塔ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
Adjacency List:每一条记录存parent_id
Path Enumerations:每一条记录存整个tree path经过的node枚举
Nested Sets:每一条记录存 nleft 和 nright
Closure Table:维护一个表,所有的tree path作为记录进行保存。
找树叶简单啊
SELECT
*
FROM
表 main
WHERE
NOT EXISTS (
SELECT * FROM 表 sub WHERE main.ID = sub.ParentID
)
也就是对于 表的 每一行, 不存在有其他行的数据, ParentID 等于 当前行的 ID
有很多种写法的,拿出包含1得,然后判断是否存在2
SELECT DISTINCT A
FROM TAB t1
WHERE B = '1' AND EXISTS (SELECT 1 FROM TAB WHERE A = t1.A and B = '2')
2)拿出1得,2得各自纪录,然后连接
SELECT t1.A
FROM (SELECT DISTINCT A FROM TAB WHERE B = '1') t1,
(SELECT DISTINCT A FROM TAB WHERE B = '2') t2
WHERE t1.A = t2.A
3)拿出1, 2 然后数个数
SELECT A
FROM TAB
WHERE B IN ('1', '2')
GROUP BY A
HAVING COUNT(DISTINCT B) = 2
with a as (
select pk_comp,name,pk_fathercomp from company
union
SELECT pk_dept,deptname,(CASE WHEN pk_fathedept=0 THEN pk_comp ELSE pk_fathedept END) as pk_comp FROM dept)
select a.name,b.name from a as b
inner join a on a.pk_comp=b.pk_fathercomp
create table T1(this varchar(10), parent varchar(10))
insert into T1(this,parent)
values ('id1',null)
,('id2',null)
,('id3','id1')
,('id4','id2')
,('id5','id3')
,('id6','id3')
,('id7','id4')
,('id8','id7')
-- sql server的cte功能
with tree(this,parent,root,depth) as (
select this,parent, this as root, 1 as depth from T1 where parent is null
union all
select a.this,a.parent, b.root, b.depth+1 as depth from T1 a, tree b where a.parent=b.this
)
select this,parent,root,depth
from tree
order by root,depth,this
树形结构的话按照算法分析的原理,是先查询父节点,然后查询器父节点的左子树(也就是句柄)然后在查询句柄的句柄。。还有你的问题我不清楚,你到底是想问什么。。你可以看看算法分析