【问题标题】:How to find an entity containing a list of id (of the other entity) in a many-to-many relation on MySql/Jpa?如何在 MySql/Jpa 上的多对多关系中找到包含(另一个实体的)id 列表的实体?
【发布时间】:2021-07-17 10:47:49
【问题描述】:

我有 3 张桌子:

  • 食谱(ID、名称)
  • Recipes_Ingredients(id、fk_recipe、fk_ingredient、数量)
  • 成分(ID、名称)

我需要找到包含所提供成分列表的所有食谱。

Es:

我提供了一个成分列表,例如 111(盐)、222(胡椒)、333(油),我需要找到包含这些成分的所有食谱。查询应该返回所有包含这些成分的食谱。

我还需要一种方法将查询报告回 Jpa。

提前致谢!

【问题讨论】:

    标签: mysql sql spring-boot jpa many-to-many


    【解决方案1】:
    SELECT fk_recipe
    FROM Recipes_Ingredients
    WHERE fk_ingredient IN (111,222,333)
    GROUP BY fk_recipe
    HAVING COUNT(DISTINCT fk_ingredient) = 3
    

    如果需要,加入 RecipesIngredients

    【讨论】:

      【解决方案2】:

      sql:

      select distinct r.fk_recipe
      from Recipes_Ingredients r
      where r.fk_ingredient in (111,222,333)
      

      在springboot jpa中,可以使用@Query

          @Query("select distinct r.fk_recipe from Recipes_Ingredients r 
                  where r.fk_ingredient in :ingredients")
          List<Long> findRecipe(@Param("ingredients") Set<Long> ingredients);
      

      当你调用 findRecipe 方法时,创建一个 Set 作为参数。

      【讨论】:

      • 您好,感谢您的回答!不幸的是,我已经尝试过这个查询,但它不起作用。他给我找到了所有那些只包含所列成分之一的食谱。我需要的是找到至少包含所提供的所有成分的所有食谱。目前,Akina 的解决方案正在发挥作用
      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 2022-08-16
      • 2019-04-07
      • 2021-06-28
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多