This is kind of difficult to describe. I have a table with two fields: Col1, Col2 with the following data:
Col1, Col2
1 10
1 11
1 12
10 1
11 1
13 1
The values in Col1 can act like a foreign key value in Col2. I want to find all the rows for a given value in Col1 where the value in Col2 appears in Col1 but where it’s Col2 value is also the given value. So for example, if I am looking for the value of 1 in Col1, the following rows are returned:
Col1, Col2
1 10
1 11
10 1
11 1
The row with Col1 set to 13 would not be returned because it does not appear in Col2 where Col1 is set to 1.
The sql I created works:
Select T1.*
From Table1 T1
Inner Join Table1 T2 On T1.Col2 = T2.Col1
Where (Exists(Select * From Table1 T3 Where (T2.Col1 = T3.Col1) And (T3.Col2 = T1.Col1)))
And (T1.Col1 = 1)
This returns duplicates of rows. I can always add the DISTINCT keyword and this will remove the duplicates. My question is whether my sql is really the correct way of selecting the records and whether it can be done without the DISTINCT keyword.
I think this may do what you want: