如何用SQL语句动态显示数据库中记录,内详...

ILoveEagles 2003-09-15 01:10:03
数据库中有三层数据,用字段“隶属”控制父子关系,用“状态”决定显示与否。
我的想法是:
1、顶层数据全部显示;
2、底层数据中只有“状态”为1显示;
3、中间层数据中,若底层有数据显示,则也显示。
不知用SQL语句可否实现,或者有其他办法?
...全文
33 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ILoveEagles 2003-09-16
  • 打赏
  • 举报
回复
非常感谢:CSDNM(决定不当CSDN经理了) 和 longji(龙寂) ,立即结分。
sjw800614 2003-09-15
  • 打赏
  • 举报
回复
你说的什么,不是太清楚!!!
longji 2003-09-15
  • 打赏
  • 举报
回复
create table #lfy(id int,data varchar(20),father int,tag char(1))
go
insert into #lfy
select 1,'a',0,'1'
union all
select 2,'b',0,'1'
union all
select 3,'c',0,'1'
union all
select 11,'aa',1,'0'
union all
select 12,'ab',1,'0'
union all
select 13,'ac',1,'0'
union all
select 21,'ba',2,'0'
union all
select 22,'bb',2,'0'
union all
select 31,'ca',3,'0'
union all
select 32,'cb',3,'0'
union all
select 111,'aaa',11,'1'
union all
select 112,'aab',11,'0'
union all
select 121,'aba',12,'0'
union all
select 122,'abb',12,'1'
--第一层father为0
--第二层tag='0'
--father为父层ID
select * from #lfy where father=0
union all
select * from #lfy where id in (select distinct father from #lfy where father>0 and tag='1')
union all
select * from #lfy where father>0 and tag='1'
CSDNM 2003-09-15
  • 打赏
  • 举报
回复
select * from tablename a ---顶层数据全部显示
where exists (
select * from tablename
where 隶属=a.id
)
and isnull(隶属,0)=0
union all
select * from tablename a ---底层数据中只有“状态”为1显示;
where not exists (
select * from tablename
where 隶属=a.id
)
and isnull(隶属,0)<>0
and 状态=1
union all
select * from tablename a ---中间层数据中,若底层有数据显示,则也显示。
where exists (
select * from tablename
where 隶属=a.id
and 状态=1
)
and isnull(隶属,0)<>0



--疑问:孤立节点如何处理?孤立节点就是没有上级也没有下级的节点,一般可以看作是顶层也是底层,上面的语句没有显示孤立节点。

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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