简体   繁体   中英

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:

  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. 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. It's quite different from your LINQ, but I assumed the result of the SQL is your target:

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. 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. That's a poorly formatted SQL statement. The ON should only be the relation between the two tables that are being joined.

Move the client_id = 104 and [language] = 'fr-FR' to additional parts of the WHERE, and you'll be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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