At least one X but no Ys Query

前端 未结 4 1018
梦如初夏
梦如初夏 2021-01-06 11:23

I come across this pattern occasionally and I haven\'t found a terribly satisfactory way to solve it.

Say I have a employee table and an review

4条回答
  •  青春惊慌失措
    2021-01-06 11:42

    The question -- return rows on side A based on nonexistence of a match in B -- (employees with No "Bad" reviews) describes an "anti-semi join". There are numerous ways to accomplish this kind of query, at least 5 I've discovered in MS Sql 2005 and above.

    I know this solution works in MSSQL 2000 and above, and is the most efficient out of the 5 ways I've tried in MS Sql 2005 and 2008. I am not sure if it will work in MySQL, but it should, as it reflects a rather common set operation.

    Note, the IN clause gives the subquery access to the employee table in the outer scope.

    SELECT EE.*
    FROM   employee EE
    WHERE
        EE.EmpKey IN (
          SELECT RR.EmpKey
          FROM   review RR
          WHERE  RR.EmpKey = EE.EmpKey
            AND  RR.ScoreCategory = 'good'
        ) 
      AND
        EE.EmpKey NOT IN (
          SELECT  RR.EmpKey 
          FROM    review RR
          WHERE   RR.EmpKey = EE.EmpKey
            AND   RR.ScoreCategory = 'bad'
        )
    

提交回复
热议问题