T-SQL: SQL to get mutual records from a single table
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 du开发者_如何学Cplicates 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:
SELECT T1.*
FROM Table1 T1
JOIN Table1 T2 ON (T1.Col2 = T2.Col1) AND (T1.Col1 = T2.Col2)
WHERE T1.Col1 = 1
I think you can drop the JOIN
and just use EXISTS
SELECT T1.*
FROM Table1 T1
WHERE 1 IN ( T1.Col1, T1.Col2 )
AND ( EXISTS ( SELECT *
FROM Table1 T2
WHERE ( T2.Col1 = T1.Col2
AND T2.Col2 = T1.Col1
) ) )
精彩评论