tags:

views:

27

answers:

2

I have a setup like this:

Username | IP
Foo      | 1.2.3.4
Bar      | 1.2.3.4
Baz      | 1.2.3.6

Say I want to find alternative accounts of the user "Foo". Something like this should return:

Username | IP
Bar      | 1.2.3.4

How would I do such a thing in one SQL query?

+2  A: 

A self join should do the trick

this will give you all users that have more than one

Select * from 
Table t1
INNER JOIN Table t2
ON t1.ip = t2.ip
and t1.Username  <> t2.Username 

you can adjust the where as you would want

e.g.

Where
 t1.UserName = 'Foo'
Conrad Frix
+1  A: 
SELECT * FROM TableName
 LEFT JOIN TableName AS TableName2 
 ON TableName2.IP = TableName.IP AND TableName2.Username != TableName.Username
 WHERE TableName.Username = 'Foo'
JamesMLV
I was typing this same code when both answers got posted...
Alex Morris
SELECT * FROM Users LEFT JOIN Users AS Users2 ON Users2.ip = Users.ip AND Users2.user != Users.user WHERE Users.user = "Foo" //Not quite working, what am I doing wrong?
Camoy
Use a single = instead of double at the end. I updated my answer.
JamesMLV