试图查询桥表的行

时间:2017-06-26 04:28:29

标签: sql sql-server

我有一个桥牌表:

PersonTagMap
ID         Autonumber
PersonFK   Integer Foreign key --to Person Table
TagFK      Integer Foreign key --to Tage Table

数据很简单:

ID       PersonFK        TAGFK
1        1               1
2        1               2
3        2               1
4        3               1
5        1               4
6        1               5

等...

我需要:

找到逻辑如下的所有PersonFK: 1 OR 2 AND 3 OR 4 AND 5 OR 6

所以有TAGS 1,3,5 or 1,3,6 or 1,4,5 or 1,4,6 or 2,3,5 or 2,3,6 or 2,4,5 or 2,4,6

的人

我试过了:

select PersonFK from PeopleTagMap PTM 
where (PTM.peopletagid = 1 or PTM.peopletagid = 2) AND 
(PTM.peopletagid =3 or PTM.peopletagid = 4) AND 
(PTM.peopletagid =5 or PTM.peopletagid = 6)

但如果我使用上面的示例数据,即使人1确实有组合1,4,5,我也没有得到回复。

任何智慧都将受到高度赞赏

2 个答案:

答案 0 :(得分:1)

请使用以下查询

    DECLARE @tblPerson AS TABLE( ID INT IDENTITY(1,1),
                             PersonFK INT,
                             TAGFK INT)
INSERT INTO @tblPerson(PersonFK,TAGFK)
     VALUES(1,1), (1,2) , (2,1),   (3,1),   (1,4),   (1,5)


SELECT PersonFK
FROM @tblPerson 
WHERE (TAGFK =1 OR TAGFK =2) 
INTERSECT
SELECT PersonFK
FROM @tblPerson 
WHERE (TAGFK =3 OR TAGFK =4) 
INTERSECT
SELECT PersonFK
FROM @tblPerson 
WHERE (TAGFK =5 OR TAGFK =6) 

答案 1 :(得分:0)

您可以将group byhaving用于此目的:

select PersonFK
from PeopleTagMap PTM 
group by PersonFK
having sum(case when PTM.peopletagid = 1 or PTM.peopletagid = 2 then 1 else 0 end) > 0 and
       sum(case when PTM.peopletagid = 3 or PTM.peopletagid = 4 then 1 else 0 end) > 0 and
       sum(case when PTM.peopletagid = 5 or PTM.peopletagid = 6 then 1 else 0 end) > 0;