5

我看过其他几个帖子问类似的问题,但坦率地说我很困惑。我正在尝试在 EntityFarmework 和 Linq 中执行以下 sql 语句,但无法使“NOT IN”和“UNION”正常工作

SELECT LmsTeam.* FROM LmsTeam
INNER JOIN Game ON LmsTeam.GameId = Game.ID 
WHERE LmsTeam.Id NOT IN 
(SELECT TeamHomeId as TeamID FROM LmsEventMatch WHERE EventId =1
UNION
SELECT TeamAwayId as TeamID FROM LmsEventMatch WHERE EventId =1)
AND LmsTeam.GameId = 1 AND LmsTeam.Active = 1

所以我有join一些 where 子句如下,但不能做NOT INandUNION子句。

from t in LmsTeams
join g in Games on t.GameId equals g.Id
  where t.GameId == 1 && t.Active == true
  select t
4

4 回答 4

3

那个怎么样:

from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true && !(
        (from m in LmsEventMatch where m.EventId == 1 select m.TeamHomeId).Union(
         from m in LmsEventMatch where m.EventId == 1 select m.TeamAwayId)
    ).Contains(t.Id)
select t

我没有测试它,因为没有你的数据上下文,但认为应该这样做。

更新

我认为你可以Union在这里避免:

from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true && !(
        LmsEventMatch.Where(m => m.EventId == 1).SelectMany(m => new int[] { m.TeamHomeId, TeamAwayId })
    ).Contains(t.Id)
select t
于 2013-03-27T10:59:56.140 回答
1

另一种解决方案是使用左外连接并保留连接列为空的记录。

下面给出一个例子:

var query = db.Categories    
  .GroupJoin(db.Products,
      Category => Category.CategoryId,
      Product => Product.CategoryId,
      (x, y) => new { Category = x, Products = y })
  .SelectMany(
      xy => xy.Products.DefaultIfEmpty(),
      (x, y) => new { Category = x.Category, Product = y })
  .Where(w => w.Product.CategoryId == null)
  .Select(s => new { Category = s.Category});
于 2014-03-04T18:46:01.560 回答
0

您可以如下编写和划分您的查询,这将轻松解决您的问题。

另请查看我的帖子:SQL to LINQ(案例 7 - 使用 IN 和 NOT IN 子句过滤数据)

//first do the union of two
var query = ((from d in  LmsEventMatch 
             where d.EventId == 1
              select d.TeamHomeId).
        Union(from e in  LmsEventMatch 
                       where e.EventId == 1
                          select e.TeamAwayId));

//than perform !contains operation for no in
var records =( from t in LmsTeams
join g in Games on t.GameId equals g.Id
  where t.GameId == 1 && t.Active == true && !query.Contains(t.Id)
  select t).ToList();

in 和 not in 的图形表示 - linq 查询

在此处输入图像描述


对于从 sql 到 linq 的转换,您可以使用:Linqer 在此处输入图像描述

于 2013-03-27T11:01:39.603 回答
0
var homeIds = LmsEventMatch.Where(em => em.Eventid == 1)
                           .Select(em => em.TeamHomeId);
var awayIds = LmsEventMatch.Where(em => em.Eventid == 1)
                           .Select(em => em.TeamAwayId);
var allIds = homeIds.Union(awayIds);

var query = LmsTeams.Where( 
                t => !allIds.Contains( t.Id ) && t.Active == 1 && t.GameId == 1);
于 2013-03-27T11:05:47.897 回答