SQL Select only rows where exact multiple relationships exist

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

    If you want to select all parents with at least a 5 and a 1, you can use:

    SELECT PARENT_ID
    FROM rel
    GROUP BY PARENT_ID
    HAVING SUM(PROP_ID = 1)
           AND SUM(PROP_ID = 5)
           AND SUM(PROP_ID NOT IN (5,1)) = 0
    

    If you need exactly one 5 and one 1, see this answer

提交回复
热议问题