Nhibernate subquery with multiple columns join

前端 未结 1 1972
无人共我
无人共我 2020-12-22 02:21

I have database structure for Plans and PlanVersions in following relationship:

 +------+                  +-------------+
 | Plan |  --------------> | Pl         


        
相关标签:
1条回答
  • 2020-12-22 03:13

    I would say, that this has solution. We have to use a bit more complex SQL in fact. This approach I've already deeply explained here:

    • Query on HasMany reference

    So, below is just a draft based on your subquery draft. What we are doing, is creating two subselects in fact (check the intended SQL here)

    PlanVersion planVersion = null;
    
    // the most INNER SELECT
    var maxSubquery = QueryOver.Of<PlanVersion>()
       .SelectList(l => l
        .SelectGroup(item => item.ParentPlan.Id)
        .SelectMax(item => item.ActiveFromDate)
        )
        // WHERE Clause
       .Where(item => item.ParentPlan.Id == planVersion.ParentPlan.Id)
       // HAVING Clause
       .Where(Restrictions.EqProperty(
          Projections.Max<PlanVersion>(item => item.ActiveFromDate),
          Projections.Property(() => planVersion.ActiveFromDate)
        ));
    
    // the middle SELECT
    var successSubquery = QueryOver.Of<PlanVersion>(() => planVersion )
        // the Plan ID
        .Select(pv => pv.ParentPlan.Id)
        .WithSubquery
        .WhereExists(maxSubquery)
        ;
    

    having this subqueries, we can ask for plan itself:

    // the most outer SELECT
    var query = session.QueryOver<Plan>()
        .WithSubquery
        .WhereProperty(p => p.Id)
        .In(successSubquery)
        .List<Plan>();
    

    There could be some minor typos, but the draft should give you clear answer how to...

    0 讨论(0)
提交回复
热议问题