sql - 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。
解决方案
如果我理解正确,您基本上是想从#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
推荐阅读
- java - 在每个春季批处理作业运行中传递相同的参数
- php - 数据库查询以填充选择字段
- c# - Ajax 请求无法访问 Api 服务器
- maven - 替换 Azure Devops 任务组中的 settings.xml
- apache-kafka - 无法连接到 Confluent Platform Schema Registry - Apache Flink SQL Confluent Avro 格式
- css - 如何解决 ASP.Net MVC 旧应用程序上的路径相关样式表导入 (prssi) 漏洞修复
- f# - 如何在 F# 中将类型声明为受约束
- python - 在 django 中实现 drf_yasg (swagger) 的问题 (AssertionError ModelSerializer)
- mysql - 在另一列中使用 group by max() 两次
- pandas - Python Flask send_from_directory 返回损坏的文件