【问题标题】:NHibernate HQL distinct and order byNHibernate HQL 不同并按顺序排序
【发布时间】:2011-05-17 09:39:44
【问题描述】:

我最近在旧代码库中从 NHibernate 1.2 升级到 3.1。我已经解决了大多数问题,但我被困在这个问题上。 (如果不对代码库进行大量更改,我就无法从 HQL 更改为另一种访问方法)。

这在 1.2 中不是问题,但升级后我遇到了以下问题。

我有以下 HQL:

select distinct c.OwnerUser from Film c order by c.OwnerUser.UserName

导致错误:

[SQL: select distinct user1_.Id as Id33_, user1_.ApplicationId as Applicat2_33_, user1_.UserName as UserName33_, user1_.LoweredUserName as LoweredU4_33_, user1_.MobileAlias as MobileAl5_33_, user1_.IsAnonymous as IsAnonym6_33_, user1_.LastActivityDate as LastActi7_33_, user1_.CreateDate as CreateDate33_, user1_.CountryCode as CountryC9_33_, user1_.PreferredEditionId as Preferr10_33_ from dbo.tbl_Content film0_ inner join dbo.vw_aspnet_Users_With_Id user1_ on film0_.OwnerUserId=user1_.Id, dbo.vw_aspnet_Users_With_Id user2_ where film0_.discriminator in ('film', 'webcamfilm', 'slideshow') and film0_.OwnerUserId=user2_.Id order by user2_.UserName] ---> System.Data.SqlClient.SqlException: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

这段代码工作正常,只是我不想要一个重复的条目。

select c.OwnerUser from Film c order by c.OwnerUser.UserName

如何编写 HQL 以获得不同的结果?

【问题讨论】:

  • 不要急于从 HQL 更改为任何其他访问方法,我们也在运行 NHibernate 3,并且我们计划最终将所有其他访问方法更改为 HQL 作为 SQL其他访问方法生成的性能不佳。

标签: nhibernate hql


【解决方案1】:

尝试指定一个连接

select distinct owner from Film c join c.OwnerUser owner order by owner.UserName

【讨论】:

    【解决方案2】:

    这个sql的错误是子句order by user2_.UserName,但是在选择列表中找不到user2_.UserName,这恰好是select distinct查询的一个约束。

    试试

    选择不同的 c.OwnerUser, c.OwnerUser.UserName 来自 Film c 订单 通过 c.OwnerUser.UserName

    然后遍历结果列表并将 OwnerUser 设为 (OwnerUser)list[i][0] 或类似

    【讨论】:

    • 谢谢,但我需要直接从查询中返回 OwnerUsers,因为已经部署的框架是如何工作的。
    • 即使我使用这个解决方案,结果也不再像我需要的那样了
    【解决方案3】:

    假设所有者用户具有唯一的 id,您可以使用以下内容:

    select c.OwnerUser from Film c where c.OwnerUser.id in ( select distinct c.OwnerUser.id from Film c) order by c.OwnerUser.UserName
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多