将两个SQL查询与INNER JOIN结合使用

时间:2016-12-17 21:53:58

标签: sql join inner-join

我想在朋友的新项目中找到共同的朋友。有两种不同的查询,我们需要将它们与INNER JOIN结合起来。

如何将这两个查询结合起来以获得项目中的共同朋友?

非常感谢。

查询#1:

SELECT * 
FROM [Register] 
WHERE RegisterId IN (SELECT MyId 
                     FROM Friends 
                     WHERE FriendId='" + Session["CurrentProfileId"] + "' 
                       AND Status = 1 
                     UNION 
                     SELECT FriendId 
                     FROM Friends
                     WHERE MyId='" + Session["CurrentProfileId"] + "' 
                       AND Status = 1)

查询#2:

SELECT * 
FROM [Register] 
WHERE RegisterId IN (SELECT MyId 
                     FROM Friends 
                     WHERE FriendId='" + Session["CurrentProfileId"] + "' 
                       AND Status = 1 
                     UNION 
                     SELECT FriendId 
                     FROM Friends 
                     WHERE MyId='" + Session["CurrentProfileId"] + "' 
                       AND Status = 1
                       AND '" + Session["UserId"] + "' != '" + Session["CurrentProfileId"] + "')

Related Link

1 个答案:

答案 0 :(得分:0)

我不明白Session [UserId]和Session [CurrentProfileId]之间有什么区别。假设你想得到一个用户列表,他们是某个特定用户@USER_ID的朋友,好吗?

SELECT r.RegisterId,r.Name
FROM Register r
  JOIN Friends f ON f.MyId=r.RegisterId and f.Status=1
WHERE f.FriendId=@USER_ID
UNION
SELECT r.RegisterId,r.Name
FROM Register r
  JOIN Friends f ON f.FriendId=r.RegisterId and f.Status=1
WHERE f.MyId=@USER_ID