【问题标题】:Return the rows(Ids) which satisfies and has both the values in IN condition返回满足并同时具有 IN 条件的行(Ids)
【发布时间】:2018-09-06 13:42:53
【问题描述】:

我有一个下面的table,其中包含名为Recipes 的样本数据,它充当其他2 tables 之间的junction table

查询 -

select recipeId, IngredientId  from Recipes where IngredientId in (1,31) order by recipeId

当我在SQL 上方声明execute 时,它在Output. 下方给出,这很好。

我必须在查询中进行哪些更改才能突出显示Output

现在为什么要6,721

作为RecipeIds6721是唯一具有both IngrdientIds[i.e. 1,31]Ids

【问题讨论】:

  • RecipeID = 6 怎么样?
  • @MJH 编辑了我的问题,请检查
  • 我认为这可能只是一个错字,但我想确保您没有错过问题中的某些内容。

标签: sql sql-server conditional-statements where-clause where-in


【解决方案1】:

您可以使用group by 子句:

select RecipeIds 
from table t
where IngrdientIds in (1, 31)
group by RecipeIds 
having count(distinct IngrdientIds) = 2;

你也可以使用min() & max()函数:

having min(IngrdientIds) = 1 and max(IngrdientIds) = 31;

【讨论】:

  • 对于上面的值(1,31) 似乎在我的最后工作,但它是否适用于IN clause 中的动态条件?
  • 请告诉我什么是count(distinct IngrdientIds) = 2
  • @PB-BitWiser。 . .它将计算唯一的IngrdientIds
  • @PB-BitWiser。 . .如果你有 IngrdientIds1, 1, 31 一样,那么它将被视为 2 而不是 3
猜你喜欢
  • 2018-03-05
  • 1970-01-01
  • 2018-10-23
  • 2021-05-03
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多