MySQL ONLY IN() equivalent clause

前端 未结 1 1936
再見小時候
再見小時候 2021-02-02 04:39

I am giving a very abstract version of my question here, so please bear with me. I have a query that will check whether a particular body has certain multiple parameters of same

相关标签:
1条回答
  • this problem is called Relational Division

    SELECT boy_id 
    FROM   boys_chocolates 
    WHERE  chocolate_id IN ('$string')
    GROUP  BY boy_id 
    HAVING COUNT(DISTINCT chocolate_id) = ? -- <<== number of chocolates specified
    

    example:

    SELECT boy_id 
    FROM   boys_chocolates 
    WHERE  chocolate_id IN (1,2,3,4)
    GROUP  BY boy_id 
    HAVING COUNT(DISTINCT chocolate_id) = 4
    
    • SQL of Relational Division

    however, if the chocolate_id is unique for every boy_id, DISTINCT keyword is optional.

    SELECT boy_id 
    FROM   boys_chocolates 
    WHERE  chocolate_id IN (1,2,3,4)
    GROUP  BY boy_id 
    HAVING COUNT(*) = 4
    

    UPDATE 1

    ...I want to choose boys from the table who have exactly the chocolates I mention. Not more not less...

    SELECT boy_id 
    FROM   boys_chocolates a
    WHERE  chocolate_id IN (1,2,3,4) AND
            EXISTS 
            (
                SELECT  1
                FROM    boys_chocolates b
                WHERE   a.boy_ID = b.boy_ID
                GROUP   BY boy_id
                HAVING  COUNT(DISTINCT chocolate_id) = 4
            )
    GROUP  BY boy_id
    HAVING COUNT(*) = 4
    
    • SQLFiddle Demo
    0 讨论(0)
提交回复
热议问题