SQL Select only rows where exact multiple relationships exist

后端 未结 10 1292
温柔的废话
温柔的废话 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:59

    This query is true even if (PARENT_ID, PROP_ID) is not unique:

    SELECT PARENT_ID FROM rel WHERE
    PROP_ID IN (5,1) AND 
    PARENT_ID NOT IN (SELECT DISTINCT PARENT_ID FROM rel WHERE PROP_ID NOT IN (5,1))
    GROUP BY PARENT_ID HAVING COUNT(DISTINCT PROP_ID) = 2
    

提交回复
热议问题