开发者

Select row matching a condition if no other rows match a different condition

Very basic, but didn't know what this type of query is called...I want a query that will basically do this (pseudo-SQL):

SELECT name 
  FROM Table  
 WHERE activity_status != 'active'  
   AND there are no rows with that same name where a开发者_StackOverflow中文版ctivity_status = 'active'  

(in other words, return names of the inactive only when not one with that name is active)

This will be used to allow users an option to reactivate inactive items, but I want to query the db to make sure that item isn't already active.


You're looking for a NOT EXISTS pattern.

"For each name that is not active, no rows exist for the same name that are active"

SELECT name FROM Table T1
WHERE activity_status != 'active'
AND
NOT EXISTS (SELECT *
        FROM Table T2
        WHERE
            T2.activity_status = 'active' AND T1.name = T2.name)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜