sql检查行是否是另一个表的子集

时间:2014-06-04 06:28:09

标签: mysql sql ms-access

你能解决我的问题吗?我有一个tblProduct,它是用于生产带贴花的物品的物料清单。 tblStock是有货的贴纸。我需要一个查询来检查哪些产品可以根据可用的贴花制造。只有所有贴花都可用时才能生产。非常感谢高级

tblProduct

    Id      decal_1         decal_2     decal_3        
    1       111             121         144
    2       104             106         144
    3       121             144         163
    4       122             144         163
    5       (null)          163         191
    6       104             121         163

tblStock

Available_decal
111
121
144
163
191

期望输出

Id
1
3
5

请注意,数字5中存在空值。这使问题变得复杂

1 个答案:

答案 0 :(得分:2)

IN检查应该

SELECT 
    * 
FROM 
    tblProduct 
WHERE 
    (decal_1 IS NULL OR decal_1 IN (SELECT Available_decal FROM tblStock))
    AND (decal_2 IS NULL OR decal_2 IN (SELECT Available_decal FROM tblStock))
    AND (decal_3 IS NULL OR decal_3 IN (SELECT Available_decal FROM tblStock))

EXISTS的另一种方式:

SELECT 
    * 
FROM 
    tblProduct 
WHERE 
    (decal_1 IS NULL OR EXISTS (SELECT 1 FROM tblStock WHERE Available_decal = decal_1))
    AND (decal_2 IS NULL OR EXISTS (SELECT 1 FROM tblStock WHERE Available_decal = decal_2))
    AND (decal_3 IS NULL OR EXISTS (SELECT 1 FROM tblStock WHERE Available_decal = decal_3))