左外连接除了匹配行之外还返回空右侧

时间:2014-01-11 21:50:43

标签: c# mysql sql linq lambda

我正在尝试创建一个查询,该查询将返回两个表的左外连接,但每次匹配时都会有一个额外的行。额外的行右侧为空。这是一个例子:

Join

这是我使用linq的当前查询(SQL中的响应也赞赏):

context.Code
       .GroupJoin(
           context.SubCode,
           code => code.CodeID,
           sub => sub.CodeID,
           (code, sub) => new
           {
               Codes = code,
               SubCodes = sub
           })
       .SelectMany(sub => sub.SubCodes.DefaultIfEmpty(),
           (code, sub) => new { Codes = code.Codes, SubCodes = sub })
       .ToList();

编辑(解决方案?):

SELECT Codes.ID, Codes.Code, SubCodes.SubCode
FROM Codes
INNER JOIN SubCodes
ON Codes.ID = SubCodes.CodeID
UNION
SELECT Codes.ID, Codes.Code, NULL
FROM Codes
ORDER BY Codes.ID

1 个答案:

答案 0 :(得分:1)

这是执行您想要的SQL:

(select c.id, c.code, sc.subCode
 from codes c join
      subcodes sc
      on c.id = sc.codeid
) union all
(select c.id, c.code, NULL
 from codes c
)