2017-01-18 221 views
0

下面是示例查詢如果IN子查詢沒有行,如何返回所有行?

Select * 
    from tb.Users u 
where u.Approved = 1 
    and u.userID IN (SELECT us.UserID us 
         FROM tb.UserStatementes us 
         WHERE us.LogDate between date1 and date2) 

,我需要選擇那些在次IN子句但是如果子查詢未返回,我需要選擇所有用戶(即忽略IN子句)

+1

您可以添加到您現有的和'OR NOT EXISTS(SELECT us.UserID我們 FROM tb.UserStatementes我們 WHERE us.LogDate DATE1和date2之間)' –

回答

6
Select * 
    from tb.Users u 
where u.Approved = 1 
    and (
    u.userID IN (SELECT us.UserID us 
         FROM tb.UserStatementes us 
         WHERE us.LogDate between date1 and date2 
         ) 
    or not exists (
     select 1 
      from tb.UserStatementes us 
      where us.LogDate between date1 and date2 
     ) 
    ) 
記錄所有用戶
1
Select * 
    from tb.Users u 
where u.Approved = 1 
    and (exists  (SELECT 1 
          FROM tb.UserStatementes us 
          WHERE us.LogDate between date1 and date2 
          AND us.USERID = u.USERID) 
     or not exists (SELECT 1 
          FROM tb.UserStatementes us 
          WHERE us.LogDate between date1 and date2) 
     )