使用LINQ简化查询

时间:2012-01-27 17:49:07

标签: sql linq

拥有以下架构: enter image description here

有没有办法简化以下查询并以更友好的版本将其转换为LINQ-SQL?

  SELECT DISTINCT(c.id_credito), c.expediente, c.status
FROM creditos AS C 
JOIN acreditados AS A ON A.id_credito = C.id_credito
WHERE A.id_acreditado NOT IN 
    (SELECT  d.id_acreditado
    FROM disposiciones_acreditados AS D)

建议?

1 个答案:

答案 0 :(得分:0)

我发现使用NOT EXISTS条件的解决方案根据this文章执行得更快。

所以我要查询的查询是:

SELECT DISTINCT(c.id_credito), c.expediente, c.status
FROM creditos AS C 
JOIN acreditados AS A ON A.id_credito = C.id_credito
WHERE NOT EXISTS
    (SELECT NULL AS EMPTY
    FROM disposiciones_acreditados AS D
    WHERE D.id_acreditado = A.id_acreditado)

使用LINQ等价物:

(from c in context.creditos
                           join a in context.acreditados on c.IDCredito equals a.IDCredito
                           where !(from d in context.disposiciones_acreditados
                                   select d.IDAcreditado).Contains(a.IDAcreditado)
                           select c).Distinct();