Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询以查找包含组的两个表之间缺少的数据_Sql_Sql Server - Fatal编程技术网

SQL查询以查找包含组的两个表之间缺少的数据

SQL查询以查找包含组的两个表之间缺少的数据,sql,sql-server,Sql,Sql Server,我已经尝试了一些方法来实现下一步的目标,但必须有一个简单的方法 假设我有烹饪食谱。每个食谱都有配料。 当工人们准备一份食谱时,他们会分批进行 我试图找出如何找到缺少哪些成分的批次,以便稍后插入到另一个表中,该表包含所有制备数据。目前,它只显示实际使用的成分的数据 以下是数据: CREATE TABLE #Repipe ( Recipe VARCHAR(1) , Ingredient VARCHAR(2) ) INSERT INTO #Repipe (Recipe, Ingre

我已经尝试了一些方法来实现下一步的目标,但必须有一个简单的方法

假设我有烹饪食谱。每个食谱都有配料。 当工人们准备一份食谱时,他们会分批进行

我试图找出如何找到缺少哪些成分的批次,以便稍后插入到另一个表中,该表包含所有制备数据。目前,它只显示实际使用的成分的数据

以下是数据:

CREATE TABLE #Repipe 
(
    Recipe VARCHAR(1)
    , Ingredient VARCHAR(2)
)

INSERT INTO #Repipe (Recipe, Ingredient)
VALUES
(1, 1)
, (1, 2)
, (1, 3)
, (1, 4)

CREATE TABLE #RecipePreparation
(
    Recipe VARCHAR(1)
    , Batch SMALLINT
    , Ingredient VARCHAR(2)
)

INSERT INTO #RecipePreparation (Recipe, Batch, Ingredient)
VALUES
(1, 1, 1)
, (1, 1, 2)
, (1, 1, 3)
, (1, 1, 4)
, (1, 2, 1)
, (1, 2, 2)
, (1, 2, 3)
, (1, 2, 4)
, (1, 3, 1)
, (1, 3, 3)
, (1, 3, 4)

DROP TABLE #RecipePreparation
DROP TABLE #Repipe

如您所见,批号3缺少配料2。

如果我理解正确,您基本上希望从
#Recipe
表中获取所有记录,这些记录在
#RecipePreparation
中没有相应的
(配方,配料)
记录

如果我正确理解你的问题,像这样的事情应该能满足你的需要。查询未经测试

SELECT *
FROM (SELECT DISTINCT Recipe, Batch FROM #RecipePreparation) xrp
    LEFT JOIN #Recipe r on r.Recipe = xrp.Recipe
    LEFT JOIN #RecipePreparation rp on rp.Recipe = xrp.Recipe AND rp.Batch = xrp.Batch AND rp.Ingredient = r.Ingredient
WHERE rp.Ingredient IS NULL

数据模型是固定的还是仍在开发中,因为理想情况下您需要的是这样的:

如果事情是固定的,那么Ruslan提供的解决方案就足够了(选择DISTINCT是为了克服批处理实体在当前模型中不显式的事实)

更改的动机是确保不会出现数据问题,从而使查询引擎能够正确优化

这也使得回答你的问题更加直接:

SELECT
  Batch.Recipe
 ,Batch.Batch
 ,RecipeIngredient.Ingredient
FROM
  Batch Batch
INNER JOIN
  RecipeIngredient RecipeIngredient
    ON RecipeIngredient.Recipe = Batch.Recipe

  EXCEPT

SELECT
  Recipe
 ,Batch
 ,Ingredient
FROM
  BatchIngredient

请标记您的sql引擎。非常感谢各位,我将在我刚开始度假时尽快检查这个。谢谢你的帮助,谢谢。工作非常好。不幸的是,我们无法修改应用程序以纠正这种情况,这本来是理想的。谢谢你的帮助!