如何从表中查找递归的自联接记录

时间:2010-01-29 16:28:45

标签: sql sql-server sql-server-2005

我有一个简单的问题让我感到难过。

我有一个主表Table X

Table X
ID
_________
1
2
3
4
5

我有一个表X的连接表,允许记录自行连接。我们称之为JoinTableX

JoinTableX
RecordAID RecordBID
--------- --------
1         2        (So Record 1 from Table X has a link to Record 2 from Table X)
1         3
1         4
2         3
2         4
3         1
3         2
4         1
4         2

那么如何编写一个SQL查询来向我显示JoinTableX中彼此具有重复依赖关系的所有记录(示例bove Table X Record 1链接到表X Record 4和Table X Record 4链接到Table X记录1.

2 个答案:

答案 0 :(得分:4)

select *
from JoinTableX a
inner join JoinTableX b on a.RecordAID = b.RecordBID 
    and a.RecordBID = b.RecordAID

答案 1 :(得分:1)

(SELECT RecordAID, RecordBID FROM JoinTableX)
INTERSECT
(SELECT RecordBID, RecordAID FROM JoinTableX)