具有复杂内部查询的HQL更新查询

时间:2015-09-04 13:49:17

标签: c# hibernate postgresql nhibernate hql

当我的成员总数为Guild.League = 0时,我正在尝试更新TournamentXP

    using (var session = sessionFactory.OpenStatelessSession())
    using (var tx = session.BeginTransaction())
    {
        const int maxLeagues = 6;
        session.CreateQuery(
            @"update Guild g set g.League = g.League + 1 where g.League < " + maxLeagues + @" 
                AND g.Id in (
                    select GuildId from (
                       select GuildId, SUM(u.TournamentXP) AS s from User u where GuildId != 0 group by u.GuildId) r
                    where r.s = 0)
        ").ExecuteUpdate();

        tx.Commit();
    }

查询在查询的第3行第48行附近抛出“Antlr.Runtime.NoViableAltException”。

原始的postgresql查询(运行正常)看起来像:

update guilds set league = league + 1 where league <= 5 
                AND id in (
                    select guild_id from (
                       select guild_id, SUM(u.tournament_xp) AS s from users u where guild_id != 0 group by u.guild_id) r
                    where r.s = 0)

如何让它在HQL中运行?

此外,如果您可以为查询提出任何优化,我将很高兴听到它。

1 个答案:

答案 0 :(得分:0)

这是因为HQL不支持FROM子句上的子查询。 它仅支持select / where子句。

因此要么使用本机SQL(或)将内部子查询从子句转换为where子句。

BTW你可以直接使用HAVING子句并避免from子句中的内部子查询,如下所示:

AND g.Id in (
 select u.GuildId from User u where u.GuildId != 0
 group by u.GuildId
 having SUM(u.TournamentXP) = 0
)