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

时间:2014-05-04 15:40:24

标签: sql

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

另一张表是Ingredients表,其中包含每种产品的成分;它包含GoodsCodeAmount等列。因此,此表将Id表中的条目的Products列作为外键。

我想要的只是查询将产品的Id作为输入,并将其他产品的所有ID与输出相同的成分(它可以是表值函数) )。

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

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

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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>)

这不会给你完全匹配,因为它只过滤掉那些原料产品中没有包含原料的产品。

您可能希望查看ALL函数以获得完全匹配,可能类似

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。所以如果您想要包含具有相同Amount和GoodsCode的所有成分,您可以尝试这样的事情获取这些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
    )
相关问题