How to return rows from left table not found in right table?

前端 未结 7 986
滥情空心
滥情空心 2020-12-23 09:09

I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will

7条回答
  •  鱼传尺愫
    2020-12-23 09:39

    This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.

    For me, the most understandable way I can think of is like so:

    --Users that bought from us 6 months ago and between 3 months ago.
    DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
    INSERT @6To3MonthsUsers
        select u.ID,opd.OrderDate
            from OrdersPaid opd
            inner join Orders o
            on opd.OrderID = o.ID
            inner join Users u
            on o.BuyerID = u.ID
            where 1=1 
            and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())
    
    --Users that bought from us in the last 3 months
    DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
    INSERT @Last3MonthsUsers
        select u.ID,opd.OrderDate
            from OrdersPaid opd
            inner join Orders o
            on opd.OrderID = o.ID
            inner join Users u
            on o.BuyerID = u.ID
            where 1=1 
            and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()
    

    Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.

    There are 2 simple ways to achieve that:

    1. Using Left Join:

      select distinct a.UserID
      from @6To3MonthsUsers a
      left join @Last3MonthsUsers b
      on a.UserID = b.UserID
      where b.UserID is null
      
    2. Not in:

      select distinct a.UserID
      from @6To3MonthsUsers a
      where a.UserID not in (select b.UserID from @Last3MonthsUsers b)
      

    Both ways will get me the same result, I personally prefer the second way because it's more readable.

提交回复
热议问题