Sql LEFT OUTER JOIN with WHERE clause

前端 未结 6 386
生来不讨喜
生来不讨喜 2020-12-10 17:01

I have two tables:

Request:

 RequestID | Msg
----------------
    5  | abc
    6  | def
    7  | ghi
    8  | jkl

6条回答
  •  时光取名叫无心
    2020-12-10 17:07

    SqlFiddle

    This answer assumes you just want the RequestId & Msg from the Request Table where there is not a record in the RequestStatus table with that RequestId and a StatusId of 2.

    You won't get extra records for Requests with multiple RequestStatus records using this query either (vs Left join).

    Using the not exists clause is faster than Except, Not In, Outer Apply, etc in this article by Aaron Bertrand - Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?

    select r.RequestId, r.Msg
      from Request r
      where not exists (
        select 1 
        from RequestStatus rs 
        where rs.StatusId = 2
          and rs.RequestId = r.RequestId
        )
    

提交回复
热议问题