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 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的