我有一个table - Network_Users
包含users
. 我正在尝试设计一个查询,允许我选择所有具有彼此链接的用户。所以每个userId-relatedUserId
关系也是一个relatedUserId-userId 关系。
用户用户
ID
Network_Users
userId
relatedUserId
谁能提出一个好的方法来做到这一点?
select *
from network_users a,
network_users b
where a.userid = b.relateduserid
and b.userid = a.relateduserid
为古老的连接语法道歉 - 对于自连接,我发现这更清楚了。
如果您想选择图表中的所有关系,您可以使用此代码
WITH REU AS
(
Select
NU.UserId ,
NU.RUserId ,
UserIdMap = Convert(varchar(max), NU.UserId) + '->' + Convert(varchar(max), NU.RUserId)
From NetworkUser As NU
--Where
--( NU.RUserId Not In ( Select NUSub.UserId From NetworkUser As NUSub ) ) -- Find Last Nodes
Union All
Select
NU.UserId ,
NU.RUserId ,
UserIdMap = Convert(varchar(max) , NU.UserId ) + '->' + REU.UserIdMap
From NetworkUser As NU
Inner Join REU On
( NU.RUserId = REU.UserId )
And
( CHARINDEX( Convert(varchar(max) , NU.UserId ) , REU.UserIdMap ) <= 0 ) -- Stop Loop
)
SELECT *
FROM REU
Go
GO
/****** Object: Table [dbo].[NetworkUser] Script Date: 3/17/2013 8:09:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NetworkUser](
[UserId] [int] NOT NULL,
[RUserId] [int] NOT NULL,
CONSTRAINT [PK_NetworkUser] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Users] Script Date: 3/17/2013 8:09:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[UserId] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
你可以得到这样的结果
4->8
6->8
7->8
1->7->8
3->7->8
6->7->8
5->6->7->8
2->5->6->7->8
4->5->6->7->8
3->4->5->6->7->8
如果您想找到双重关系,请使用它
Select
*
From NetworkUser As N1
Inner Join NetworkUser As N2 On
( N1.UserId = N2.RUserId And N1.RUserId = N2.UserId )