我一直在尝试获取以下SQL
SELECT *
FROM dbo.VirtualMachines vm
WHERE vm.SequenceId IN (
SELECT MAX(SequenceId) FROM dbo.VirtualMachines GROUP BY RequestId
)
AND vm.DeletedBy IS NULL
...进入LINQ查询以与NHibernate一起使用。
我已经能够根据一个腐蚀的子查询得到这种工作的变体:
var allvms = from vms in this.currentSession.Query<Entities.VirtualMachine>()
where vms.DeletedBy == null
where vms.Id == (
from activeVms in this.currentSession.Query<Entities.VirtualMachine>()
where activeVms.RequestId == vms.RequestId
orderby activeVms.Id descending
select activeVms.Id).First()
orderby vms.RequestId
select vms;
......这给了我......
SELECT *
FROM dbo.VirtualMachines vm
WHERE vm.SequenceId IN (
SELECT TOP 1 zvm.SequenceId From dbo.VirtualMachines zvm WHERE zvm.RequestId = vm.RequestId ORDER BY zvm.SequenceId DESC
)
AND vm.DeletedBy IS NULL
...但是我宁愿使用MAX()
版本(具有配置文件的SQL Server),这对我正在使用的数据集来说是一个更有效的查询。不幸的是,我无法弄清楚如何纠缠LINQ给我查询。
我知道我能做到:
from vms in this.currentSession.Query<Entities.VirtualMachine>()
group vms by vms.RequestId into vmReqs
select new {
LatestSeqId = vmReqs.Max(vms => vms.SequenceId)
}
给了我子选择(SELECT MAX(SequenceId) [...]
),但是我看不出如何将它与我已经做过IN
的查询结合起来。我可能在SQL语言集中接近这个问题,我正试图像在SQL中那样处理查询,并且还有其他一些我错过的技术。
答案 0 :(得分:1)
这样的事情:
var subQuer = from vms in this.currentSession.Query<Entities.VirtualMachine>()
group vms by vms.RequestId into vmReqs
select vmReqs.Max(vms => vms.SequenceId);
var outerQuery = from vm in this.currentSession.Query<Entities.VirtualMachine>()
where subQuery.Contains(vm.SequenceId) && vm.DeletedBy == null;