为子项的匹配父项选择所有子表ID

时间:2014-12-01 17:14:39

标签: sql sql-server-2012

我在下面有这些表格。(为了便于阅读,我省略了其他不必要的列)

团队 - TeamID,TeamName

TeamMembers - TeamMemberID,TeamID,MemberName

BoothVisitLog - BoothVisitLogID,BoothID,访问者(MemberID)

例如假设一个ID为1的TeamMember访问了一个BoothID 1.现在我想找到同一团队的任何成员是否已经访问过该展位。

我写了下面的查询,工作正常。但我更倾向于编写更好的优化查询而不是使用Sub Query。有什么方法可以使用join来实现同样的目标吗?

SELECT * FROM BoothVisitLog BVL INNER JOIN
(
    SELECT TM.MemberID FROM TeamMembers TM 
    INNER JOIN Teams T ON TM.TeamID = T.TeamID 
    WHERE T.TeamID IN
    (
        SELECT TM.MemberID FROM TeamMembers TM 
        INNER JOIN Teams T ON TM.TeamID = T.TeamID 
        WHERE TM.MemberID = 1
    )
) TTM ON BVL.VisitedBy = TTM.MemberID AND BVL.BoothID = 1

1 个答案:

答案 0 :(得分:1)

由于展位号为1,唯一重要的是会员ID为1的团队

这将给出你想要的结果

SELECT BL.* FROM BoothVisitLog BL
JOIN TeamMembers TM
ON  BL.BoothID =1
AND TM.MemberID = BL.VisitedBy
JOIN
( select TeamID from TeamMembers where MemberID =1) T
ON T.TeamID = TM.TeamID

如果您想知道团队成员也可以看到会员ID 1访问过的所有展位的结果,您可以在BoothVisitLog表上使用self join获取结果。< / p>

 SELECT BL2.* FROM BoothVisitLog BL1
JOIN BoothVisitLog BL2
on BL1.BoothID = BL2.BoothID 
AND BL1.VisitedBy =1
JOIN TeamMembers TM
on TM.MemberID = BL2.VisitedBy
JOIN
( select TeamID 
  from TeamMembers where MemberID =1) T
ON T.TeamID = TM.TeamID