SQL Select only rows where exact multiple relationships exist

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

    SELECT PARENT_ID
    FROM rel
    GROUP BY PARENT_ID
    HAVING
      COUNT(PROP_ID)=2 AND
      COUNT(DISTINCT case when PROP_ID IN ( 1, 5 ) then PROP_ID end)=2
    

    This will select all PARENT_ID that have exactly two rows, with exactly two, non duplicated, PROP_ID that match.

提交回复
热议问题