我正在寻找以下SQL的Linq等价物:
SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
FROM MyTable t0
LEFT OUTER JOIN MyTable t1
ON t0.Fk_CompanyId = t1.Fk_CompanyId AND t0.CheckedUtc < t1.CheckedUtc
WHERE t1.Fk_CompanyId IS NULL
AND t0.CheckedUtc IS NOT NULL
我与Linq最亲密的是:
from t0 in MyTable
join t1 in MyTable on t0.Fk_CompanyId equals t1.Fk_CompanyId into t1tmp
from t1 in t1tmp.DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null && t0.CheckedUtc < t1.CheckedUtc
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }
...产生以下SQL(稍微重新格式化):
SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
FROM MyTable AS t0
LEFT OUTER JOIN MyTable AS t1
ON t0.Fk_CompanyId = t1.Fk_CompanyId
WHERE (t1.Fk_CompanyId IS NULL)
AND (t0.CheckedUtc IS NOT NULL)
AND (t0.CheckedUtc < t1.CheckedUtc)
这些并不完全相同。 (t0.CheckedUtc < t1.CheckedUtc
被推送到WHERE
。)当我在t0.CheckedUtc < t1.CheckedUtc
上进行外部左连接时,这会在连接的右侧产生NULL值。当我使用WHERE
进行过滤时,会删除我感兴趣的所有NULL值。
透视:我正在尝试使用最新的 CheckedUtc 查找 MyTable 中的行,如果有任何非NULL的行,则按 Fk_CompanyId <分组< / em>的。我想为每个 Fk_CompanyId 添加一行。有几个&#34;可能的重复&#34;只处理找到最新的CheckedUtc (但不是它们各自的行),或者假设 CheckedUtc 是非NULL。
所以:如何在Linq中对非等号谓词执行等效连接?
答案 0 :(得分:1)
试试这个
from t0 in MyTable
From t1 in MyTable( x=>x.Fk_CompanyId=t0.Fk_CompanyId && x.CheckedUtc > t0.CheckedUtc ).DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }