[英]NHibernate / LINQ select MAX in subquery?
我一直在尝试获取以下SQL
SELECT *
FROM dbo.VirtualMachines vm
WHERE vm.SequenceId IN (
SELECT MAX(SequenceId) FROM dbo.VirtualMachines GROUP BY RequestId
)
AND vm.DeletedBy IS NULL
...到用于NHibernate的LINQ查询中。
我已经能够根据相关的子查询对这种工作方式进行修改:
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中那样处理查询,而我错过了其他一些技巧。
像这样:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.