Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.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 - Fatal编程技术网

Sql 如何根据父表在子表中的子记录查找父表的重复记录?

Sql 如何根据父表在子表中的子记录查找父表的重复记录?,sql,Sql,我在SQL中有两个表,一个是Products表,其中包含一些产品的记录;每个产品的Id都是独一无二的 另一张表是成分表,包含每种产品的成分;它包含GoodsCode、Amount等列。因此,该表将Products表中某个条目的Id列作为外键 我所需要的只是一个查询,将一个产品的Id作为输入,并给出其他产品的所有Id,这些Id的成分与输出相同,它可以是一个表值函数 目标是根据相同产品的成分找到它们的ID 我不知道这是否是一个好的直接解决方案 提前感谢。首先,您需要获得产品中成分的成分: Selec

我在SQL中有两个表,一个是Products表,其中包含一些产品的记录;每个产品的Id都是独一无二的

另一张表是成分表,包含每种产品的成分;它包含GoodsCode、Amount等列。因此,该表将Products表中某个条目的Id列作为外键

我所需要的只是一个查询,将一个产品的Id作为输入,并给出其他产品的所有Id,这些Id的成分与输出相同,它可以是一个表值函数

目标是根据相同产品的成分找到它们的ID

我不知道这是否是一个好的直接解决方案


提前感谢。

首先,您需要获得产品中成分的成分:

Select ingredientId from ingredients where productId = <your product id>
然后你需要使用这些成分来寻找其他类似的产品

select productId from products p 
join ingredients i on p.productId = i.productId 
where i.ingredientId in (
    Select ingredientId from ingredients where productId = <your product id>)
这不会给你提供精确的匹配,因为它只会过滤掉那些含有原产品中未包含的成分的产品

您可能希望查看所有函数以获得精确匹配,可能类似于

select productId from products p
join ingredients i on p.productId = i.productId 
where i.ingredientId = ALL(
    Select ingredientId from ingredients where productId = <your product id>)
更新

< >修改成分的同一性,只需改变内部查询,只包括要考虑的成分的ID。因此,如果您希望包含所有具有相同数量和商品代码的成分,您可以尝试以下方法获得这些ID:

select ingredientId from ingredients i1 join (
    select GoodsCode, Amount from ingredients i where i.productId = <your prod id>) as i2 
on i1.GoodsCode = i2.GoodsCode and i1.Amount = i2.Amount
然后将此子查询插入到上面的中,我们得到:

select productId from products p
join ingredients i on p.productId = i.productId 
where i.ingredientId = ALL(
    select ingredientId from ingredients i1 join (
        select GoodsCode, Amount from ingredients i 
            where i.productId = <your prod id>) as i2 
        on i1.GoodsCode = i2.GoodsCode and i1.Amount = i2.Amount
    )

然后你的查询到底是做什么的?!您只是返回产品和成分的内部联接,其中productId=您使用的是哪个数据库引擎?我在问题中提到了SQL.tnx作为答案,但成分的相同性不仅仅基于IngredenId。它基于Amount和GoodsCode字段。更新了修改相同标准的说明,您使用的是哪种DBMS?博士后?神谕