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

HQL update query with complex inner queries

我正在尝试更新 Guild.League 时其成员总数 TournamentXP = 0:

    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 中工作?

此外,如果您能提出任何优化查询的建议,我将很高兴听到。

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

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

顺便说一句,您可以直接使用 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
)