【问题标题】:Grails query with associations - find all in a table where id is not in another table带有关联的 Grails 查询 - 在一个表中查找所有 id 不在另一个表中
【发布时间】:2025-11-26 01:10:03
【问题描述】:

我需要能够找到表中的所有项目,其中每个项目的 id 不在关系映射表中。换句话说,我有一个表,其中每一行都有一个 id。如果该 id 在地图表中,它不应该出现在我的列表中。

我正在考虑查询我的地图表以获取其中的所有 id,然后转身查询我的主表以排除任何具有该 id 的项目......所以类似于:

select * from Main where id not in(select main_id from Map);

有没有一种好的方法可以通过 findBy 方法或条件构建器查询来使用 grails?

【问题讨论】:

    标签: sql hibernate grails criteria


    【解决方案1】:

    如果您使用的是 Hibernate,您应该可以使用 HQL 来做到这一点,使用 not in 和子查询 (here's a page of examples):

    from Main as main where main.id not in (select map.main_id from Map as map)
    

    基于this page,相信你需要在Main.findAll方法中执行这个查询:

    def results = Main.findAll("from Main as main where main.id not in (select map.main_id from Map as map)")
    

    【讨论】:

    • 我以为我以前做过这个,但它不能正常工作。我显然做错了什么,因为这确实有效。谢谢。
    最近更新 更多