首页 > 解决方案 > SQL 查询以查找包含组的 2 个表之间的缺失数据

问题描述

我已经尝试了几种方法来实现下一步,但必须有一个简单的方法。

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

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

这是数据:

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。

标签: sqlsql-server

解决方案


如果我理解正确,您基本上是想从#Recipe表中获取所有没有相应(Recipe, Ingredient)记录的记录#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

推荐阅读