I have a table in SQL Server to record the IP of all the members’ login of my website.
ID MEMBER IP
---------------------------------------
1 member1 1.1.1.1
2 member2 2.2.2.2
3 member3 1.1.1.1
4 member3 3.3.3.3
5 member4 3.3.3.3
I want to figure out a way to search for associated member and their associated IP.
First example,
- member1 logged in from 1.1.1.1 before
- member3 logged in from 1.1.1.1 and 3.3.3.3 before
- member4 logged in from 3.3.3.3 before
So, For member1:
- Associated members: member1, member3, member4
- Associated IPs : 1.1.1.1, 3.3.3.3
For member2, associated member is member2 and associated IP is 2.2.2.2 .
This association system is to help manage fake players and the number of members is big ( ~100k ). So loading time is a big issue.
My question:
- Is there a SQL Query to generate the list of associated members and associated IPs?
=======Table to test======
CREATE TABLE [dbo].[tblAssociation](
[ID] [int] NULL,
[Member] [nvarchar](50) NULL,
[IP] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT INTO [tblAssociation] VALUES(1,'member1','1.1.1.1')
INSERT INTO [tblAssociation] VALUES(2,'member2','2.2.2.2')
INSERT INTO [tblAssociation] VALUES(3,'member3','1.1.1.1')
INSERT INTO [tblAssociation] VALUES(4,'member3','3.3.3.3')
INSERT INTO [tblAssociation] VALUES(5,'member4','3.3.3.3')
======shankar’s suggestion====
SELECT T1.Member, T1.IP, T2.Member
FROM tblAssociation T1
INNER JOIN tblAssociation T2 ON T1.IP = T2.IP
AND T1.Member = 'member1'
if you try, I can only get associated member = member1, member3.
member4 is not there, but he should be associated because member4 and member3 connected to 3.3.3.3 before
Building on the same statement as shankar_pratap, following
CTEwould get you all related members to a given member. The real difficulty here is in knowing when to stop the recursion. For the recursion to stop, bothq.ID <> a.IDandq.OriginalID <> r.IDare required.SQL Statement
Result