左外连接多个On语句

时间:2015-12-16 00:45:44

标签: c# sql sql-server linq tsql

我已经在这几个小时了。这就是我尝试过的:

List<SoccerTeamsModel> incompleteFootballTeams = (from fbt in db.footballTeams
    join fbct in db.footballCustomTeams
    on fbt.team_id equals fbct.team_id && fbct.client_id == clientId && fbct.language == selectedLanguage into t
    from ct in t.DefaultIfEmpty()
    where fbt.league_id == leagueId
    orderby fbt.name ascending
    select new SoccerTeamsModel
    {
        TeamId = fbt.team_id,
        ClientId = ct.client_id, 
        etc...
    }).ToList();

我正在尝试复制的SQL查询:

  SELECT *
  FROM [SoccerData].[dbo].[footballTeams] AS fbt
  LEFT OUTER JOIN [SoccerData].[dbo].[footballCustomTeams] AS fbct
  ON fbt.team_id = fbct.team_id AND fbct.client_id = 104 AND fbct.[language] = 'fr-FR'  
  WHERE fbt.league_id = 8
  ORDER BY fbt.name ASC

让我感到困扰的似乎是试图将所有多个“on”条款放入其中。我已经看过一些例子,但它们不包括Left Outer Join。我似乎无法把两者放在一起。

2 个答案:

答案 0 :(得分:1)

我认为这个查询应该提供一些接近你的SQL表达式。它与您的LINQ完全不同,但我认为SQL的结果是您的目标:

var clientId = 104;
var lang = "fr-FR";
var leagueId = 8;

// Find teams in specifiec league
// Equivalent to this step in SQL: WHERE fbt.league_id = 8
var leagueTeams = footballTeams.Where(fbt => fbt.league_id == leagueId).ToList();

// Find teams that fulfill required conditions
// Equivalent to the On condition in SQL
var teams = footballCustomTeams
.Where(fbct => leagueTeams.Any(fbt => fbct.team_id == fbt.team_id) &&
                fbct.client_id == clientId &&
                fbct.language == lang)
.Select(fbct => new { TeamId = fbct.team_id, ClientId = fbct.client_id });

不是重现连接,而是简单地将LINQ查询划分为更多的子查询,每个子查询都缩小了结果。可能需要稍微调整,因为我无法访问您的模型,只是试图从样本中推断出来。

答案 1 :(得分:0)

您不需要创建多个ON语句。这是一个格式不正确的SQL语句。 ON应该只是正在连接的两个表之间的关系。

client_id = 104[language] = 'fr-FR'移动到WHERE的其他部分,你会没事的。