查找表的子组中的所有行

时间:2015-03-11 12:51:59

标签: sql sql-server database sql-server-2008

我很难用语言解释这一点。 我想做什么: 我有下表

employerID, userID
45          1
48          1
53          1
45          2
55          2

我想构建一个返回行的查询

employerID, userID
45          1
48          1
53          1
45          2
and omit
55          2

雇主id为55不在包含userID 1的行中。

我想查找userID = 2的所有行,其employeeID位于userID = 1的所有行的组中

我想指定用户ID 1和2。

4 个答案:

答案 0 :(得分:2)

所以你想找到userID = 1或至少有一条记录存在同一employerIDuserID = 1的所有行?

然后你可以使用这个完全相同的SQL:

SELECT employerID, userID
FROM dbo.TableName t
WHERE t.userID = 1  -- either userID = 1
OR                  -- or userID = 2 but with another record with userID = 1 and the same  employerID
(
    t.userID = 2 AND EXISTS            
    (
       SELECT 1 FROM dbo.TableName t1
       WHERE t1.userID = 1
       AND   t1.employerID = t2.employerID
    )
)

答案 1 :(得分:1)

我不确定,但它似乎是你想得到的:

Select * from tableA a
Where userID = 2
And not exists (
select 1 from tableA 
where employerID = a.employerID 
and userID = 1)

答案 2 :(得分:1)

我认为一个简单的自我内部联接可以解决这个问题:

SELECT a.employerID, a.userID
FROM tbl a INNER JOIN tbl b
ON(a.employerID = b.employerID)
WHERE (a.userID = 1 AND b.userID = 2)
OR (a.userID = 2 AND b.userID = 1)

答案 3 :(得分:1)

还有一个版本:

DECLARE @t TABLE ( EmpID INT, UserID INT )

INSERT  INTO @t
VALUES  ( 45, 1 ),
        ( 48, 1 ),
        ( 53, 1 ),
        ( 45, 2 ),
        ( 55, 2 )


SELECT  * FROM    @t
WHERE   EmpID NOT IN ( SELECT EmpID FROM @t WHERE UserID = 2
                       EXCEPT
                       SELECT EmpID FROM @t WHERE UserID = 1 )

输出:

EmpID   UserID
45      1
48      1
53      1
45      2