SQL Select only rows where exact multiple relationships exist

后端 未结 10 1266
温柔的废话
温柔的废话 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.

    0 讨论(0)
  • 2020-12-06 02:58

    Hope this will help you:

    SELECT p.PARENT_ID , r.PROP_ID FROM rel r LEFT JOIN parent p ON p.PARENT_ID = r.PARENT_ID WHERE r.PROP_ID = 5 OR r.PROP_ID = 1
    
    0 讨论(0)
  • 2020-12-06 02:59

    Assuming (PARENT_ID, PROP_ID) is unique:

    SELECT r1.PARENT_ID
    FROM rel r1
    INNER JOIN rel r2 ON r1.PARENT_ID = r2.PARENT_ID AND r2.PROP_ID = 5 
    INNER JOIN rel r3 ON r1.PARENT_ID = r3.PARENT_ID AND r3.PROP_ID = 1
    GROUP BY r1.PARENT_ID
    HAVING COUNT(*) = 2
    

    Or,

    SELECT parent.PARENT_ID
    FROM parent
    INNER JOIN
    (
        SELECT PARENT_ID
        FROM rel
        WHERE PROP_ID IN (1,5)
        GROUP BY PARENT_ID
        HAVING COUNT(*) = 2
    ) good ON parent.PARENT_ID = good.PARENT_ID
    LEFT OUTER JOIN rel bad ON parent.PARENT_ID = bad.PARENT_ID 
        AND bad.PROP_ID NOT IN (1,5)
    WHERE bad.PARENT_ID IS NULL
    

    Or even,

    SELECT DISTINCT parent.PARENT_ID
    FROM parent
    INNER JOIN rel r2 ON parent.PARENT_ID = r2.PARENT_ID AND r2.PROP_ID = 5 
    INNER JOIN rel r3 ON parent.PARENT_ID = r3.PARENT_ID AND r3.PROP_ID = 1
    LEFT OUTER JOIN rel r0 ON parent.PARENT_ID = r0.PARENT_ID 
        AND r0.PROP_ID NOT IN (1,5)
    WHERE r0.PARENT_ID IS NULL
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题