如何过滤表格

时间:2013-03-17 14:06:20

标签: mysql sql

我有table - Network_Users,其中包含users之间的关联。我正在尝试设计一个查询,允许我选择所有彼此链接的用户。所以每个userId-relatedUserId关系也是一个relatedUserId-userId关系。

用户
用户id

Network_Users
用户id
relatedUserId

有人能建议一个好方法吗?

3 个答案:

答案 0 :(得分:3)

select *
from    network_users  a, 
        network_users  b
where   a.userid    =   b.relateduserid
and     b.userid    =   a.relateduserid

为古老的连接语法道歉 - 对于自连接,我发现有点清楚。

答案 1 :(得分:1)

如果您想要选择图表中的所有关系 可以使用此代码

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-&GT; 8

6-&GT; 8

7-&GT; 8

1→7-&GT; 8

3→7-&GT; 8

6-&将7-&GT; 8

5→6-&将7-&GT; 8

2→5→6-&将7-&GT; 8

4-将5-&GT; 6-&将7-&GT; 8

3→4-将5-&GT; 6-&将7-&GT; 8

答案 2 :(得分:0)

如果你想找到双重关系

,请使用它
Select 
*
From NetworkUser As N1
Inner Join NetworkUser As N2 On 
      ( N1.UserId = N2.RUserId And N1.RUserId = N2.UserId )