如何从两个用户之间的连接表中检索连接用户的集群?

发布于 2024-09-29 13:21:07 字数 303 浏览 2 评论 0原文

该表由连接在一起的成对用户组成。以下是一个假设的示例:

user1, user2
a, b
a, c
c, a
c, d
d, e
a, e
j, n
g, n
f, n

通过从表中随机选取一个用户(user1 或 user2),我想检索所选用户所属的整个连接集群。例如,如果选择了用户 d,则查询(或算法)应返回连接

a, b
a, c
c, a
c, d
d, e
a, e

有谁知道如何形成查询语句或创建算法来检索连接集群?

谢谢你!

The table consists of pairs of users which are connected together. The following is a hypothetical example:

user1, user2
a, b
a, c
c, a
c, d
d, e
a, e
j, n
g, n
f, n

By randomly picking up a user from the table (user1 or user2) I would like to retrieve the whole cluster of connections to which the selected user belongs. For example if the user d is selected the query (or an algorithm) should return connections

a, b
a, c
c, a
c, d
d, e
a, e

Does anyone know how to form a query statement or create an algorithm to retrieve the connections cluster?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉生梦死 2024-10-06 13:21:07

通过使用递归 CTE,如下所示:

with combinedusers as 
(select user1 userX, user2 userY from usertable union
 select user2 userX, user1 userY from usertable)
, relatedusers as 
(select c.userX, 
        c.userY, 
        convert(varchar(max),'\' + c.userX + '\' + c.userY + '\') hierarchy 
        from combinedusers c where userX = 'd' 
 union all
 select c.userX, 
        c.userY, 
        convert(varchar(max),r.hierarchy  + c.userY + '\') hierarchy 
        from combinedusers c 
        join relatedusers r 
        on c.userX = r.userY and charindex('\' + c.userY + '\',r.hierarchy)=0)
select * from
(select userX, userY from relatedusers union 
 select userY, userX from relatedusers) r where userX < userY

By using a recursive CTE, like so:

with combinedusers as 
(select user1 userX, user2 userY from usertable union
 select user2 userX, user1 userY from usertable)
, relatedusers as 
(select c.userX, 
        c.userY, 
        convert(varchar(max),'\' + c.userX + '\' + c.userY + '\') hierarchy 
        from combinedusers c where userX = 'd' 
 union all
 select c.userX, 
        c.userY, 
        convert(varchar(max),r.hierarchy  + c.userY + '\') hierarchy 
        from combinedusers c 
        join relatedusers r 
        on c.userX = r.userY and charindex('\' + c.userY + '\',r.hierarchy)=0)
select * from
(select userX, userY from relatedusers union 
 select userY, userX from relatedusers) r where userX < userY
与酒说心事 2024-10-06 13:21:07

在 SQL 中对树和更一般的图形进行建模很棘手,但可以完成。

你可以用谷歌搜索“部分爆炸SQL”关键字,你会发现很多参考资料。

您可能会在此处找到一种在 MySql 中对非常相似的问题进行建模的方法。

Modeling trees and more general graphs in SQL is tricky, but can be done.

You may google for the "part explosions SQL" keywords, and you'll find a lot of references.

You may find a way to model a very similar problem in MySql here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文