SQL Select only rows where exact multiple relationships exist

后端 未结 10 1279
温柔的废话
温柔的废话 2020-12-06 02:06

This is closely related to this question, but adds another requirement.

Given a parent table \'parent\'

╔════════════╦════════╗
║ PARENT_ID  ║ NAME           


        
10条回答
  •  借酒劲吻你
    2020-12-06 02:49

    With two nested subqueries, like this..

     Select pa.Id
     From parents pa
     Where not exists -- This ensures that all specifies properties exist
        (Select * From property y
         Where propertyId In (1,5)
             And Not Exists
                 (Select * From parentProperty
                  Where parentId = pa.parentId 
                      And propertyId = y.propertyId ))
       And not exists -- This ensures that only specified list of properties exist
        (Select * From parentProperty
         Where parentId = pa.parentId 
            And propertyId Not In (1,5) )
    

    The first one reads "Show me all the parents where there is not a property in the specified list of properties that is not in the parent properties table for the specified parent...."

    The second subquery reads: "also make sure that there does not exist a record in the parentProperties table for that parent for any property that is not in the specified list."

提交回复
热议问题