即使连接表中不存在记录,也要返回记录

时间:2015-06-04 08:39:04

标签: sql sql-server sql-server-2012

我有一个包含三个表的SQL Server数据库:

GroupID GroupTitle
  1     Group 1
  2     Group 2
  3     Group 3
  4     Group 4

MEMBERS

MemberID MemberName
19       Jon
20       Marie
21       Andrew

成员组

MembersGroupID GroupID  MemberID
 221              1      20
 231              1      21

我制作了left join并得到了以下结果:

GroupID GroupTitle  MemberID IsPartOfGroup MemberName
1       Group 1     20       Yes           Marie
1       Group 1     21       Yes           Andrew
2       Group 2     NULL     No            NULL
3       Group 3     NULL     No            NULL
4       Group 4     NULL     No            NULL

这是我的加入:

select g.GroupID
,g.GroupTitle
,mg.MemberID
,IsPartOfGroup = case when mg.MembersGroupID is null then 'No' else 'Yes' end
from groups  g
left join membergroups mg on g.GroupID = mg.GroupID
left join members m on  m.memberid = mg.MemberID

但我想要的是以下结果:

GroupID GroupTitle  MemberID IsPartOfGroup MemberName
1       Group 1     19       No            Jon
2       Group 2     19       No            Jon
3       Group 3     19       No            Jon
4       Group 4     19       No            Jon
1       Group 1     20       Yes           Marie
2       Group 2     20       No            Marie
3       Group 3     20       No            Marie
4       Group 4     20       No            Marie
1       Group 1     21       Yes           Andrew
2       Group 2     21       No            Andrew
3       Group 3     21       No            Andrew
4       Group 4     21       No            Andrew

换句话说,我希望得到所有成员和他们所属的团体以及他们不属于的团体。

这可能吗?

2 个答案:

答案 0 :(得分:1)

首先需要cross joinleft join MemberGroups表。试试这个:

select g.GroupID,
       g.GroupTitle,
       m.MemberID,
       m.MemberName,
       case when mg.MembersGroupID is null then 'No' else 'Yes' end as IsPartOfGroup
from GROUPS g
cross join MEMBERS m
left join MEMBER_GROUPS mg on g.GroupID = mg.GroupID and m.MemberID = mg.MemberID

答案 1 :(得分:0)

select g.GroupID
,g.GroupTitle
,mg.MemberID
,IsPartOfGroup = case when mg.MembersGroupID is null then 'No' else 'Yes' end
from groups cross join membergroups 
left join members m on  m.memberid = mg.MemberID