简体   繁体   English

左外部联接,带有多个On语句

[英]Left Outer Join with Multiple On Statements

I've been on this for hours now. 我已经花了几个小时了。 This is what I've tried: 这是我尝试过的:

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();

the SQL query i'm trying to copy: 我尝试复制的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

What's messing me up it seems is trying to put in all the multiple "on" clauses. 令我感到困惑的是,它试图插入所有多个“ on”子句。 I've seen some examples but they don't include the Left Outer Join. 我已经看到了一些示例,但其中不包括左外部联接。 I can't seem to put the two together. 我似乎无法将两者放在一起。

I think this query should provide something close to you SQL expression. 我认为该查询应该提供一些与您的SQL表达式接近的东西。 It's quite different from your LINQ, but I assumed the result of the SQL is your target: 它与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 });

Instead of reproducing the join I simply divided the LINQ query into more subqueries that each narrows the results down. 与其复制连接,我只是将LINQ查询分为多个子查询,每个子查询缩小了结果范围。 May need slight adjustments as I didn't have access to your model and only tried to infer that from the sample. 可能需要稍作调整,因为我无权访问您的模型,而只是尝试从样本中推断出来。

You don't need to make those multiple ON statements. 您不需要使这些多个ON语句。 That's a poorly formatted SQL statement. 那是格式不正确的SQL语句。 The ON should only be the relation between the two tables that are being joined. ON应该仅是要连接的两个表之间的关系。

Move the client_id = 104 and [language] = 'fr-FR' to additional parts of the WHERE, and you'll be fine. client_id = 104[language] = 'fr-FR'移到WHERE的其他部分,就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM