weixin_52389391 2022-03-31 21:28 采纳率: 42.9%
浏览 107
已结题

sql server数据库中的两个ID之间是否存在联系

ID1 是否认识 ID2
张三 认识 李四
王五 认识 李四
马六 认识 王五

跪. 求,大。神,类似这种数据,如果数据比较多的情况下如何查询张三与马六之间的关联

  • 写回答

2条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-03-31 22:26
    关注

    可以用with递归,注意环的处理,比如

    with t as (
    select '3' id1,'4' id2 union all
    select '5' id1,'4' id2 union all
    select '6' id1,'5' id2),
    tt as (
    select id1,id2 from t
    union all
    select id2,id1 from t
    ),
    cte as (
    select distinct '0' id1,id1 id2,id1 root_node, 0 lvl from tt where id1='3'
    union all
    select tt.id1 ,tt.id2,cte.root_node,lvl+1 from tt  join  cte on tt.id1=cte.id2
    where lvl<10
    )
    select distinct cte.root_node,id2 from cte where id2='6'
    

    img

    上面这个sql就是用'3'来找是否和'6'有关系,只看10层,不设限的话可能会有无限循环。
    有必要的话,这个sql稍加改造,可以拼个关系链出来


    下面这个就是从张3到马6的10层以内最短路径

    with t as (
    select '3' id1,'4' id2 union all
    select '5' id1,'4' id2 union all
    select '6' id1,'5' id2),
    tt as (
    select id1,id2 from t
    union all
    select id2,id1 from t
    ),
    cte as (
    select distinct '0' id1,id1 id2,cast(id1 as VARCHAR(100)) root_node,cast(id1 as VARCHAR(100)) path, 0 lvl from tt where id1='3'
    union all
    select tt.id1 ,tt.id2,cte.root_node,cast(cte.path+'/'+tt.id2  as VARCHAR(100)) path,lvl+1 from tt  join  cte on tt.id1=cte.id2
    where lvl<10
    )
    select top 1 root_node,id2,path from cte where id2='6' order by lvl;
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月15日
  • 已采纳回答 4月7日
  • 创建了问题 3月31日

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上