【问题标题】:To find records which are contains all comma-separated list of Id's SQL Server查找包含 ID 的 SQL Server 的所有逗号分隔列表的记录
【发布时间】:2016-12-26 12:03:11
【问题描述】:

它有 2 个这样的表:

t_recipe:

RecipeId        Name              InsertDate 
----------------------------------------------
1             Mutton            9/6/2015 0:00
2             Veg Biryani       9/5/2015 0:00

t_recipe_ingredient:

RecipeId      IngrId          InsertDate
----------------------------------------------
1             200               9/6/2015 0:00
1             201               9/5/2015 0:00
1             101               9/4/2015 0:00
1             103               9/3/2015 0:00
2             100               9/2/2015 0:00
2             500               9/6/2015 0:00
2             202               9/5/2015 0:00
2             200               9/4/2015 0:00

现在当我使用以下查询时:

select *
from t_recipe r
    join t_recipe_ingredient i ON r.RecipeID = i.RecipeId
where i.IngrId in (200, 201)

我得到了两个食谱的输出,但是它应该只给我羊肉,因为它是包含两种成分的。似乎我的查询正在检查至少一个匹配项,但是我希望它只返回那些包含 in 子句中所有成分的食谱。

【问题讨论】:

  • 我认为你弄错了样本数据,因为它们似乎都有 201 和 200 的行。
  • 也添加预期的结果!

标签: sql sql-server-2008 join in-clause


【解决方案1】:

您需要按您的食谱分组,并且只选择具有两种成分的组

select r.RecipeId, r.Name, r.InsertDate  
from t_recipe r 
join t_recipe_ingredient i ON r.RecipeID = i.RecipeId 
where i.IngrId in (200,201)
group by r.RecipeId, r.Name, r.InsertDate
having count(distinct i.IngrId) = 2

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多