在数据库表中查找匹配集

时间:2015-04-23 01:22:18

标签: sql sql-server tsql

我在(SQL Server 2014)数据库中有一个包含FirstID和SecondID列的联结表。给定一个特定的FirstID,我想从表中找到所有其他具有等效SecondID集的FirstID(即使该集合为空)。 样本数据:

FirstId      SecondId
1            1
1            2
2            3
3            1
3            2
...          ...

对于样本数据,如果我指定FirstID = 1,那么我希望结果集中出现3。

到目前为止,我已经尝试了以下内容,除了空集之外,它的效果非常好:

SELECT FirstSecondEqualSet.FirstId
FROM FirstSecond FirstSecondOriginal
INNER JOIN FirstSecond FirstSecondEqualSet ON FirstSecondOriginal.SecondId = FirstSecondEqualSet.SecondId
WHERE FirstSecondOriginal.FirstId = @FirstId 
    AND FirstSecondEqualSet.FirstId != @FirstId
GROUP BY FirstSecondEqualSet.FirstId
HAVING COUNT(1) = (SELECT COUNT(1) FROM FirstSecond WHERE FirstSecond.FirstId = @FirstId)

2 个答案:

答案 0 :(得分:1)

这是一种方法。它计算每个firstid的值的数量,然后加入secondid

select fs2.firstid
from (select fs1.*, count(*) over (partition by firstid) as numseconds
      from firstsecond fs1
      where fs1.firstid = @firstid
     ) fs1 join
     (select fs2.*, count(*) over (partition by firstid) as numseconds
      from firstsecond fs2
     ) fs2
     on fs1.secondid = fs2.secondid and fs1.numseconds = fs2.numseconds
group by fs2.firstid
having count(*) = max(fs1.numseconds);

答案 1 :(得分:1)

我认为它与关系部门有关,没有剩余部分(RDNR)。请参阅Dwain Camps的这篇伟大article作为参考。

DECLARE @firstId INT = 1

SELECT
    f2.FirstId
FROM FirstSecond f1
INNER JOIN FirstSecond f2 
    ON f2.SecondId = f1.SecondId
    AND f1.FirstId <> f2.FirstId
WHERE
    f1.FirstId = @firstId
GROUP BY f2.FirstId
HAVING COUNT(*) = (SELECT COUNT(*) FROM FirstSecond WHERE FirstId = @firstId)