2014-09-29 85 views
1

我想下面的SQL轉換爲QueryOver主查詢的使用性能:NH QueryOver - 子查詢

Select 1 
From myTable mt 
Where mt.ForeignKey in (select ID from otherTable ot where ot.ID = R.ID) 

我想裏面的EXISTS/NOT EXISTS語句像使用此子查詢:

select * from table R where .... AND EXISTS (query above) 

目前,我有這樣的:

mainQuery.WithSubquery.WhereExists(QueryOver.Of<myTable>() 
        .Where(mt => mt.ForeignKey) 
        .WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId))); 

我創造了這個查詢作爲子查詢,我要精讀主要查詢。 問題是,該表的別名爲R是由主查詢調用的表,我不知道如何訪問表(NHibernate模型)R(在上面的查詢中不可訪問)的列,所以我的問題是:

如何從主查詢中獲取值並在子查詢中使用它們。我認爲這隻能通過內聯創建子查詢來實現(如mainQuery.WithSubquery.Where(..)或者smith。類似),但我不能看到最好的方法是什麼。我感謝任何幫助!

在此先感謝!

回答

1

的技巧是使用適當的別名,父查詢:

// the alias 
myTable R = null; 

mainQuery 
    .WithSubquery 
     .WhereExists(QueryOver 
     .Of<myTable>(() => R) // the Alias in place 
     .Where(mt => mt.ForeignKey) 
     .WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId))); 

注意,不能完全肯定的mainQuery一部分,但在一般這裏的解決辦法是這樣的:

// I. the outer query ALIAS 
Employee emplyoee = null; 

// II. the subquery - using the alias 
var subQuery = QueryOver.Of<Contact>() 
    .Select(x => x.ID) 
    .Where(x => x.Related.ID == emplyoee.ID); // use alias 

// III. declare the outer query and use the above alias 
var query = session.QueryOver<Employee>(() => emplyoee) // declare alias 
    .WithSubquery 
     .WhereExists(subQuery); // put both together 

同時檢查this以獲得更多想法

+0

感謝您使用別名提示!在您的幫助下,通過查看代碼庫中的其他代碼,我設法解決了這個問題! – Philipp 2014-09-29 07:01:45

+0

很好看;;)享受NHibernate,真棒工具;) – 2014-09-29 07:02:13