簡體   English   中英

NHibernate / LINQ在子查詢中選擇MAX?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM