项目使用NHibernate2.1.0。今天遇到一个很闹心的问题,我们有一个带分组的分页查询

var q = Session.CreateQuery(@"select t.PMM,t.RetailPrice, ...
                                from WarehouseDetail as t
                               where ...
                               group by t.PMM,t.RetailPrice")
                .SetFirstResult(start)
                .SetMaxResults(limit);

由于UI控件的需要,还得把符合上面那个查询条件的总的记录数查出来,但是下面这个语句不行

long total = Session.CreateQuery(@"select count(*)
                                     from WarehouseDetail as t
                                    where ...
                                    group by t.PMM,t.RetailPrice")
                    .UniqueResult<long>();

因为使用了分组之后,上面那个HQL返回的是每个分组的记录数,而不是总的记录数,所以上面那个语句会报“query did not return a unique result: 3”的异常,意思是查询结果是3条数据。
按照以往写普通SQL语句的思路,我们会想把它改成下面这种子查询的形式

long total = Session.CreateQuery(@"select count(*) 
                                     from (select t.PMM
                                             from WarehouseDetail as t
                                            where ...
                                            group by t.PMM,t.RetailPrice)")
                    .UniqueResult<long>();

但是很可惜,NHibernate还不支持这种from子查询。
另一种写法,是使用count distict

long total = Session.CreateQuery(@"select count(distinct t.PMM || t.RetailPrice)
                                     from WarehouseDetail as t
                                    where ...")
                    .UniqueResult<long>();

可是TNND NHibernate 居然不支持在count()里面进行字符串连接操作!我诅咒NHibernate项目组一辈子买方便面都只有调料包!!
最后没法子,搞了一个有点无厘头的语句

long total = Session.CreateQuery(@"select sum(count(*)/count(*))
                                     from WarehouseDetail as t
                                    group by t.PMM,t.RetailPrice");
                    .UniqueResult<long>();

 

posted on 2010-03-12 15:01  1-2-3  阅读(4901)  评论(4编辑  收藏  举报