日期:2014-05-20  浏览次数:20695 次

★ 请教 SQL左连接 加条件 的 linq 写法.
SELECT [t0].[UserID], [t1].[KoshinUserID] AS [KoshinUserID2] 
FROM [dbo].[User] AS [t0] 
LEFT OUTER JOIN 
[dbo].[UserProfile] AS [t1] on [t0].[UserID] = [t1].[UserID] And [t1].[[DelFlg]] = 0 //此出为重要点
WHERE [t0].[UserAccount] = '7' AND [t0].[DelFlg] = 0

请教上面的SQL的写法.


我试着用以下这个的写法.
 var userTbl = from a in iResumeDB.User
  join b in iResumeDB.UserProfile on a.UserID equals b.UserID into co
  from b in co.DefaultIfEmpty()
where a.UserAccount == userAccount && a.DelFlg == 0 && b.DelFlg == 0 select new
  {
  a,
  b
  };

但出来的SQL是:
SELECT [t0].[UserID], [t1].[KoshinUserID] AS [KoshinUserID2] 
FROM [dbo].[User] AS [t0] 
LEFT OUTER JOIN 
[dbo].[UserProfile] AS [t1] on [t0].[UserID] = [t1].[UserID] 
WHERE [t0].[UserAccount] = '7' AND [t0].[DelFlg] = 0 AND [t1].[DelFlg] = 0 //此出为重要点


上记SQL 仍然没对.T1 完全左连接,如果T1 没数据,那么AND [t1].[DelFlg] = 0 将不符合条件.
整个SQL将检索不出数据出来.

请教高手;



------解决方案--------------------
试试这样是不是你想要的结果?
var userTbl = from a in iResumeDB.User
join b in iResumeDB.UserProfile on a.UserID equals b.UserID into co
from b in co.Where(b=>b.DelFlg==0).DefaultIfEmpty()
where a.UserAccount == userAccount && a.DelFlg == 0
select new
{
 a,
b
};